<?php

namespace Admin\Controller;

use Org\Util\ArrayList;

class WorkorderController extends AdminbaseController {

    function _initialize() {
        parent::_initialize();
        $this->currentModel = D("Workorder");
    }

    //首页
    public function index() {

        $requestMap = $this->convertRequestToMap();

        $map["wo.workorder_type"] = array('elt','7');
        $this->assign("begin_time", $_REQUEST["wo#create_time-egt"]);
        $this->assign("end_time", $_REQUEST["wo#create_time-elt"]);

        //用户
        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();
//        echo($user["employee_id"]);
//        $prescriber=D("Employee")->where("prescriber=$userId" and "employee_id=$userId")->find();

        //分页
        $map["status"] = array('gt','-1');
//        if(!in_role(array("1"),$user['role'])){
//            $map["wo.enterprise_code"] = array('eq',$user["enterprise_code"]);
//        }
        $map["wo.enterprise_code"] = array('eq',$user["enterprise_code"]);
        $count = $this->currentModel->getListCount($requestMap, $map);
        $page = $this->page($count, 10);
        //获取workorder列表
        $workorderList = $this->currentModel->queryForList($page, $requestMap, $map);
        $this->assign("statusEnum", C("WORKORDER_STATUS"));
        $this->assign("typeEnum", C("WORKORDER_TYPE"));
        $this->assign('user', $user);

        $this->assign('workorderList', $workorderList);
        $this->assign("page", $page->show('Admin', $this->parameter));
        $this->assign("status", $_REQUEST["wo#status"]);
        $this->assign("type", $_REQUEST["wo#workorder_type"]);

        $enterprise=D("Enterprise")->where(array('enterprise_code'=>$user["enterprise_code"]))->find();
        $orthosisProcess = explode(',',$enterprise["orthosis_process"]);
        $this->assign('orthosisProcess', $orthosisProcess);
        $prosthesisProcess = explode(',',$enterprise["prosthesis_process"]);
        $this->assign('prosthesisProcess', $prosthesisProcess);
        $this->display();

    }

    public function indexProsthesis() {

        $requestMap = $this->convertRequestToMap();

        $map["wo.workorder_type"] = array('egt','8');
        $this->assign("begin_time", $_REQUEST["wo#create_time-egt"]);
        $this->assign("end_time", $_REQUEST["wo#create_time-elt"]);

        //用户
        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();
//        echo($user["employee_id"]);
//        $prescriber=D("Employee")->where("prescriber=$userId" and "employee_id=$userId")->find();

        //分页
        $map["status"] = array('gt','-1');
        if(!in_role(array("1"),$user['role'])){
            $map["wo.enterprise_code"] = array('eq',$user["enterprise_code"]);
        }
        $count = $this->currentModel->getListCount($requestMap, $map);
        $page = $this->page($count, 10);
        //获取workorder列表
        $workorderList = $this->currentModel->queryForList($page, $requestMap, $map);
        $this->assign("statusEnum", C("WORKORDER_STATUS"));
        $this->assign("typeEnum", C("WORKORDER_TYPE"));
        $this->assign('user', $user);

        $this->assign('workorderList', $workorderList);
        $this->assign("page", $page->show('Admin', $this->parameter));
        $this->assign("status", $_REQUEST["wo#status"]);
        $this->assign("type", $_REQUEST["wo#workorder_type"]);

        $enterprise=D("Enterprise")->where(array('enterprise_code'=>$user["enterprise_code"]))->find();
        $orthosisProcess = explode(',',$enterprise["orthosis_process"]);
        $this->assign('orthosisProcess', $orthosisProcess);
        $prosthesisProcess = explode(',',$enterprise["prosthesis_process"]);
        $this->assign('prosthesisProcess', $prosthesisProcess);
        $this->display("index");

    }

    public function home() {

//        $requestMap = $this->convertRequestToMap();


        //用户
        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();

//        echo($user["employee_id"]);
//        $prescriber=D("Employee")->where("prescriber=$userId" and "employee_id=$userId")->find();

        //分页
        $map["wo.workorder_type"] = array('elt','7');
        $map["wo.status"] = array('gt','-1');
        if(!in_role(array("1"),$user['role'])){
            $map["wo.enterprise_code"] = array('eq',$user["enterprise_code"]);
        }
//        $count = $this->currentModel->getListCount($requestMap, $map);
//        $page = $this->page(1, C("DEFAULT_PAGE_SIZE"));
        //获取workorder列表

        $field = "wo.*, pt.patient_name, pt.sex, pt.age, pt.diagnosis, creator.admin_name as creator, sales.admin_name as sales, examinator.admin_name as examinator, prescriber.admin_name as prescriber, reviewer.admin_name as reviewer, auditor.admin_name as auditor";
        $workorderList = D("Workorder")->alias("wo")
            ->join("left join __PATIENT__ pt on pt.patient_id = wo.patient_id")
//            ->join($rx)
            ->join("left join __ADMIN__ creator on creator.employee_id = wo.creator_id")
            ->join("left join __ADMIN__ sales on sales.employee_id = wo.sales_id")
            ->join("left join __ADMIN__ examinator on examinator.employee_id = wo.examinator_id")
            ->join("left join __ADMIN__ prescriber on prescriber.employee_id = wo.prescriber_id")
            ->join("left join __ADMIN__ reviewer on reviewer.employee_id = wo.reviewer_id")
            ->join("left join __ADMIN__ auditor on auditor.employee_id = wo.auditor_id")
            ->join("left join __ADMIN__ ap on ap.user_id = wo.processing_id")
            ->join("left join __ADMIN__ ad on ad.user_id = wo.delivery_id")
//            ->join("left join __PROCESS__ process on process.process_id = wo.process_id")
//            ->join("left join __PAY__ pay on pay.pay_id = wo.pay_id")
            ->where($map)
            ->order("wo.create_time desc")
            ->limit("0,3")
//            ->field("wo.*,cus.nickname,p.product_name,cus.doctor_name,cus.hospital_name,pay.out_trade_no")
//            ->field("wo.*, pt.patient_name, pt.sex, pt.age, pt.diagnosis, emp.employee_name, pt.completed as patient_completed, eb.completed as exam_basic_completed, eb.update_time as exam_basic_update_time, em.completed as exam_measure_completed, em.update_time as exam_measure_update_time, ea.completed as exam_analysis_completed, ea.update_time as exam_analysis_update_time")
//                ->field("wo.*, pt.patient_name, pt.sex, pt.age, pt.diagnosis, emp.employee_name, ap.admin_name as processing_name, ad.admin_name as delivery_name, pt.completed as patient_completed, eb.completed as exam_basic_completed, eb.update_time as exam_basic_update_time, em.completed as exam_measure_completed, em.update_time as exam_measure_update_time")
            ->field($field)
            ->select();

        $this->assign("statusEnum", C("WORKORDER_STATUS"));
        $this->assign("typeEnum", C("WORKORDER_TYPE"));
        $this->assign('user', $user);

        $this->assign('workorderList', $workorderList);

        $map1["wo.workorder_type"] = array('egt','8');
        $workorderList1 = D("Workorder")->alias("wo")
            ->join("left join __PATIENT__ pt on pt.patient_id = wo.patient_id")
//            ->join($rx)
            ->join("left join __ADMIN__ creator on creator.employee_id = wo.creator_id")
            ->join("left join __ADMIN__ sales on sales.employee_id = wo.sales_id")
            ->join("left join __ADMIN__ examinator on examinator.employee_id = wo.examinator_id")
            ->join("left join __ADMIN__ prescriber on prescriber.employee_id = wo.prescriber_id")
            ->join("left join __ADMIN__ reviewer on reviewer.employee_id = wo.reviewer_id")
            ->join("left join __ADMIN__ auditor on auditor.employee_id = wo.auditor_id")
            ->join("left join __ADMIN__ ap on ap.user_id = wo.processing_id")
            ->join("left join __ADMIN__ ad on ad.user_id = wo.delivery_id")
//            ->join("left join __PROCESS__ process on process.process_id = wo.process_id")
//            ->join("left join __PAY__ pay on pay.pay_id = wo.pay_id")
            ->where($map1)
            ->order("wo.create_time desc")
            ->limit("0,3")
//            ->field("wo.*,cus.nickname,p.product_name,cus.doctor_name,cus.hospital_name,pay.out_trade_no")
//            ->field("wo.*, pt.patient_name, pt.sex, pt.age, pt.diagnosis, emp.employee_name, pt.completed as patient_completed, eb.completed as exam_basic_completed, eb.update_time as exam_basic_update_time, em.completed as exam_measure_completed, em.update_time as exam_measure_update_time, ea.completed as exam_analysis_completed, ea.update_time as exam_analysis_update_time")
//                ->field("wo.*, pt.patient_name, pt.sex, pt.age, pt.diagnosis, emp.employee_name, ap.admin_name as processing_name, ad.admin_name as delivery_name, pt.completed as patient_completed, eb.completed as exam_basic_completed, eb.update_time as exam_basic_update_time, em.completed as exam_measure_completed, em.update_time as exam_measure_update_time")
            ->field($field)
            ->select();
        $this->assign('workorderList1', $workorderList1);

        $finishedOrderMap["fo#status-neq"] = -2;
        $finishedOrderMap["fp#class_id-neq"] = "17";
        $finishedOrderMap["fo.enterprise_code"] = $user["enterprise_code"];
        $page = $this->page(5, 5);
        $finishedOrderList = D("FinishedOrder")->queryForList($page, $finishedOrderMap);

        $this->assign('finishedOrderList', $finishedOrderList);
        $this->assign("defaultEnum", C("INVOICE_TYPE"));

        $enterprise=D("Enterprise")->where(array('enterprise_code'=>$user["enterprise_code"]))->find();
        $orthosisProcess = explode(',',$enterprise["orthosis_process"]);
        $prosthesisProcess = explode(',',$enterprise["prosthesis_process"]);
        $this->assign('orthosisProcess', $orthosisProcess);
        $this->assign('prosthesisProcess', $prosthesisProcess);
//        $this->assign("page", $page->show('Admin', $this->parameter));
        $this->display("home");

    }

    public function printTemplate() {
        $templateList = D("PrintTemplate")->order("print_template_id desc")->select();
        $this->assign('templateList', $templateList);
        $this->display("printTemplate");

    }

    public function viewWorkorder() {
        $id = $_REQUEST["id"];
        $workorder = $this->currentModel->queryById($id);
        $patientInfo = D("Patient")->queryById($workorder["patient_id"]);

        $examAnalysis = D("ExamAnalysis")->queryById($workorder["exam_analysis_id"]);

        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();
        $employeeList = D("admin")->where(array('enterprise_code'=>$user["enterprise_code"],'granted'=>1))->select();
        foreach ($employeeList as $singleEmployee){
            if($singleEmployee["employee_id"] == $workorder["examinator_id"]){
                $examinator = $singleEmployee;
            }
            if($singleEmployee["employee_id"] == $workorder["creator_id"]){
                $creator = $singleEmployee;
            }
            if($singleEmployee["employee_id"] == $workorder["sales_id"]){
                $sales = $singleEmployee;
            }
            if($singleEmployee["employee_id"] == $workorder["prescriber_id"]){
                $prescriber = $singleEmployee;
            }
            if($singleEmployee["employee_id"] == $workorder["reviewer_id"]){
                $reviewer = $singleEmployee;
            }
            if($singleEmployee["employee_id"] == $workorder["auditor_id"]){
                $auditor = $singleEmployee;
            }
        }

//        $examinator = D("admin")->where(array('employee_id'=>$workorder["examinator_id"]))->find();
//        $creator = D("admin")->where(array('employee_id'=>$workorder["creator_id"]))->find();
//        $sales = D("admin")->where(array('employee_id'=>$workorder["sales_id"]))->find();
//        $prescriber = D("admin")->where(array('employee_id'=>$workorder["prescriber_id"]))->find();
        if($workorder["workorder_type"] == 1){
            if($workorder["version"] == 1){
                $page1 = D("PrintTemplate")->queryById(1);
                $page2 = D("PrintTemplate")->queryById(2);
            }
            if($workorder["version"] == 2){
                $page1 = D("PrintTemplate")->queryById(26);
                $page2 = D("PrintTemplate")->queryById(27);
                $order0 = D("PrintTemplate")->queryById(7);
                $order1 = D("PrintTemplate")->queryById(8);
                $order2 = D("PrintTemplate")->queryById(9);
                $order3 = D("PrintTemplate")->queryById(10);
                $order4 = D("PrintTemplate")->queryById(11);
                $order5 = D("PrintTemplate")->queryById(12);
                $order6 = D("PrintTemplate")->queryById(13);
                $order7 = D("PrintTemplate")->queryById(14);
                $order8 = D("PrintTemplate")->queryById(15);
                $order9 = D("PrintTemplate")->queryById(16);
            }


            $examBasic = D("ExamBasic")->queryById($workorder["exam_basic_id"]);
            $mapEb['class_name'] = array('like', array('exam_basic', 'all'), 'or');
            $formDictEb = D("FormDict")->queryForList($mapEb);
            foreach ($formDictEb as $vo) {
                $formDictEb[$vo["index"]] = $vo["name"];
            }
            $gaitArr = explode(',', $examBasic["gait"]);
            $gait = "";
            foreach ($gaitArr as $vo) {
                if($gait == ""){
                    $gait = $formDictEb["gait_" . $vo];
                }else{
                    $gait = $gait . "," . $formDictEb["gait_" . $vo];
                }
            }
            if(!isNullOrEmpty($examBasic["notegait"])){
                $gait = $gait . "   备注:" . $examBasic["notegait"];
            }
            $examBasic["gait"] = $gait;

            $examBasicCP = D("ExamBasicCp")->queryById($workorder["exam_basic_cp_id"]);
            $examMeasure = D("ExamMeasure")->queryById($workorder["exam_measure_id"]);

            $rx = D("Rx")->queryById($workorder["rx_id"]);
            $map['class_name'] = array('like', array('rx', 'all'), 'or');
            $formDictRx = D("FormDict")->queryForList($map);
            foreach ($formDictRx as $vo) {
                $formDictRx[$vo["index"]] = $vo["name"];
            }

            $afotype_outArr = explode(',', $rx["afotype_out"]);
            $afotype_out = "";
            foreach ($afotype_outArr as $vo) {
                if($afotype_out == ""){
                    $afotype_out = $formDictRx["afotype_" . $vo];
                }else{
                    $afotype_out = $afotype_out . "," . $formDictRx["afotype_" . $vo];;
                }
            }

            $afotype_inArr = explode(',', $rx["afotype_in"]);
            $afotype_in = "";
            foreach ($afotype_inArr as $vo) {
                if($afotype_in == ""){
                    $afotype_in = $formDictRx["afotypein_" . $vo];
                }else{
                    $afotype_in = $afotype_in . "," . $formDictRx["afotypein_" . $vo];;
                }
            }

            $dorsal_supArr = explode(',', $rx["dorsal_sup"]);
            $dorsal_sup = "";
            foreach ($dorsal_supArr as $vo) {
                if($dorsal_sup == ""){
                    $dorsal_sup = $formDictRx["dorsal_sup_" . $vo];
                }else{
                    $dorsal_sup = $dorsal_sup . "," . $formDictRx["dorsal_sup_" . $vo];;
                }
            }

            $flexArr = explode(',', $rx["flex"]);
            $flex = "";
            foreach ($flexArr as $vo) {
                if($flex == ""){
                    $flex = $formDictRx["flex_" . $vo];
                }else{
                    $flex = $flex . "," . $formDictRx["flex_" . $vo];;
                }
            }

            $mould_outArr = explode(',', $rx["mould_out"]);
            $mould_out = "";
            foreach ($mould_outArr as $vo) {
                if($mould_out == ""){
                    $mould_out = $formDictRx["mould_" . $vo];
                }else{
                    $mould_out = $mould_out . "," . $formDictRx["mould_" . $vo];;
                }
            }

//            $mould_inArr = explode(',', $rx["mould_in"]);
//            $mould_in = "";
//            foreach ($mould_inArr as $vo) {
//                if($mould_in == ""){
//                    $mould_in = $formDictRx["mould_" . $vo];
//                }else{
//                    $mould_in = $mould_in . "," . $formDictRx["mould_" . $vo];;
//                }
//            }

            $cutline_outArr = explode(',', $rx["cutline_out"]);
            $cutline_out = "";
            foreach ($cutline_outArr as $vo) {
                if($cutline_out == ""){
                    $cutline_out = $formDictRx["cutline_" . $vo];
                }else{
                    $cutline_out = $cutline_out . "," . $formDictRx["cutline_" . $vo];;
                }
            }

            $cutline_inArr = explode(',', $rx["cutline_in"]);
            $cutline_in = "";
            foreach ($cutline_inArr as $vo) {
                if($cutline_in == ""){
                    $cutline_in = $formDictRx["cutlinein_" . $vo];
                }else{
                    $cutline_in = $cutline_in . "," . $formDictRx["cutlinein_" . $vo];;
                }
            }

            $pelma_outArr = explode(',', $rx["pelma_out"]);
            $pelma_out = "";
            foreach ($pelma_outArr as $vo) {
                if($pelma_out == ""){
                    $pelma_out = $formDictRx["pelma_" . $vo];
                }else{
                    $pelma_out = $pelma_out . "," . $formDictRx["pelma_" . $vo];;
                }
            }

            $pelma_inArr = explode(',', $rx["pelma_in"]);
            $pelma_in = "";
            foreach ($pelma_inArr as $vo) {
                if($pelma_in == ""){
                    $pelma_in = $formDictRx["pelma_" . $vo];
                }else{
                    $pelma_in = $pelma_in . "," . $formDictRx["pelma_" . $vo];;
                }
            }

            $this->assign("rx", $rx);
            $this->assign("afotype_out", $afotype_out);
            $this->assign("afotype_in", $afotype_in);
            $this->assign("dorsal_sup", $dorsal_sup);
            $this->assign("flex", $flex);
            $this->assign("mould_out", $mould_out);
//            $this->assign("mould_in", $mould_in);
            $this->assign("cutline_out", $cutline_out);
            $this->assign("cutline_in", $cutline_in);
            $this->assign("pelma_out", $pelma_out);
            $this->assign("pelma_in", $pelma_in);

        }
        if($workorder["workorder_type"] == 2){
            if($workorder["version"] == 1){
                $page1 = D("PrintTemplate")->queryById(3);
                $page2 = D("PrintTemplate")->queryById(4);
            }
            if($workorder["version"] == 2){
                $page1 = D("PrintTemplate")->queryById(17);
                $page2 = D("PrintTemplate")->queryById(18);
                $order0 = D("PrintTemplate")->queryById(7);
                $order1 = D("PrintTemplate")->queryById(8);
                $order2 = D("PrintTemplate")->queryById(20);
                $order3 = D("PrintTemplate")->queryById(21);
                $order4 = D("PrintTemplate")->queryById(22);
                $order5 = D("PrintTemplate")->queryById(23);
                $order6 = D("PrintTemplate")->queryById(24);
                $order7 = D("PrintTemplate")->queryById(25);
                $order8 = D("PrintTemplate")->queryById(15);
                $order9 = D("PrintTemplate")->queryById(16);

            }

            $examBasic = D("ExamBasicSpine")->queryById($workorder["exam_basic_spine_id"]);
            $examMeasure = D("ExamMeasureSpine")->queryById($workorder["exam_measure_spine_id"]);

            $rx = D("RxCommon")->queryById($workorder["rx_id"]);
            $map['class_name'] = array('like', array('rx_tlso', 'all'), 'or');
            $formDictRxCommon = D("FormDict")->queryForList($map);
            foreach ($formDictRxCommon as $vo) {
                $formDictRxCommono[$vo["index"]] = $vo["name"];
            }

            $mouldArr = explode(',', $rx["rt22"]);
            $mould = "";
            foreach ($mouldArr as $vo) {
                if($mould == ""){
                    $mould = $formDictRxCommon["mould_" . $vo];
                }else{
                    $mould = $mould . "，" . $formDictRxCommon["mould_" . $vo];;
                }
            }
            $this->assign("rx", $rx);
            $this->assign("mould", $mould);
        }
        if($workorder["workorder_type"] == 3){
            $page1 = D("PrintTemplate")->queryById(5);
//            echo($workorder["exam_basic_cp_plus_id"]);
            $examBasic = D("ExamBasicCpPlus")->queryById($workorder["exam_basic_cp_id"]);
//            $examMeasure = D("ExamMeasureSpine")->queryById($workorder["exam_measure_spine_id"]);
        }
        if($workorder["workorder_type"] == 4){

            $page1 = D("PrintTemplate")->queryById(28);
            $page2 = D("PrintTemplate")->queryById(29);
            $order0 = D("PrintTemplate")->queryById(7);
            $order1 = D("PrintTemplate")->queryById(8);
            $order2 = D("PrintTemplate")->queryById(30);
            $order3 = D("PrintTemplate")->queryById(31);
            $order4 = D("PrintTemplate")->queryById(32);
            $order5 = D("PrintTemplate")->queryById(23);
            $order6 = D("PrintTemplate")->queryById(24);
            $order7 = D("PrintTemplate")->queryById(25);
            $order8 = D("PrintTemplate")->queryById(15);
            $order9 = D("PrintTemplate")->queryById(16);

            $examBasic = D("ExamBasicCommon")->queryById($workorder["exam_basic_id"]);
            $examMeasure = D("ExamMeasureCommon")->queryById($workorder["exam_measure_id"]);

            $rx = D("RxCommon")->queryById($workorder["rx_id"]);
            $map['class_name'] = array('like', array('rx_sco', 'all'), 'or');
            $formDictRxSco = D("FormDict")->queryForList($map);
            foreach ($formDictRxSco as $vo) {
                $formDictRxSco[$vo["index"]] = $vo["name"];
            }
            if(!isNullOrEmpty($rx['rt0'])){
                $step1Num = $rx['rt0'];
                $step1 = D("FormDict")->where(array('index'=>'step1_'.$step1Num))->find();
                $step2 = D("FormDict")->where(array('index'=>'step2_'.$step1["name"].'_'.$rx['rt'.($step1Num+1)]))->find();
                $this->assign("design", $step2["name"]);
            }

            $this->assign("rx", $rx);
            $this->assign("mould", $mould);
        }

        if($workorder["workorder_type"] == 5 || $workorder["workorder_type"] == 6){

            $page1 = D("PrintTemplate")->queryById(36);
            $page2 = D("PrintTemplate")->queryById(37);
            $order0 = D("PrintTemplate")->queryById(7);
            $order1 = D("PrintTemplate")->queryById(8);
            $order2 = D("PrintTemplate")->queryById(38);
            $order3 = D("PrintTemplate")->queryById(39);
            $order4 = D("PrintTemplate")->queryById(40);
            $order5 = D("PrintTemplate")->queryById(12);
            $order6 = D("PrintTemplate")->queryById(13);
            $order7 = D("PrintTemplate")->queryById(14);
            $order8 = D("PrintTemplate")->queryById(15);
            $order9 = D("PrintTemplate")->queryById(16);

            $examBasic = D("ExamBasicCommon")->queryById($workorder["exam_basic_id"]);
            $examMeasure = D("ExamMeasureCommon")->queryById($workorder["exam_measure_id"]);

            $rx = D("RxCommon")->queryById($workorder["rx_id"]);

            $this->assign("rx", $rx);
        }

        if($workorder["workorder_type"] == 7){

            $page1 = D("PrintTemplate")->queryById(41);
            $page2 = D("PrintTemplate")->queryById(42);
            $order0 = D("PrintTemplate")->queryById(7);
            $order1 = D("PrintTemplate")->queryById(8);
            $order2 = D("PrintTemplate")->queryById(43);
            $order3 = D("PrintTemplate")->queryById(44);
            $order4 = D("PrintTemplate")->queryById(45);
            $order5 = D("PrintTemplate")->queryById(12);
            $order6 = D("PrintTemplate")->queryById(13);
            $order7 = D("PrintTemplate")->queryById(14);
            $order8 = D("PrintTemplate")->queryById(15);
            $order9 = D("PrintTemplate")->queryById(16);

            $examBasic = D("ExamBasicCommon")->queryById($workorder["exam_basic_id"]);
            $examMeasure = D("ExamMeasureCommon")->queryById($workorder["exam_measure_id"]);

            $rx = D("RxCommon")->queryById($workorder["rx_id"]);
            $this->assign("rx", $rx);
        }

        if($workorder["workorder_type"] == 9){

            $page1 = D("PrintTemplate")->queryById(46);
            $page2 = D("PrintTemplate")->queryById(47);
            $order0 = D("PrintTemplate")->queryById(7);
            $order1 = D("PrintTemplate")->queryById(8);
            $order2 = D("PrintTemplate")->queryById(43);
            $order3 = D("PrintTemplate")->queryById(44);
            $order4 = D("PrintTemplate")->queryById(45);
            $order5 = D("PrintTemplate")->queryById(12);
            $order6 = D("PrintTemplate")->queryById(13);
            $order7 = D("PrintTemplate")->queryById(14);
            $order8 = D("PrintTemplate")->queryById(15);
            $order9 = D("PrintTemplate")->queryById(16);

            $examBasic = D("ExamBasicCommon")->queryById($workorder["exam_basic_id"]);
            $examMeasure = D("ExamMeasureCommon")->queryById($workorder["exam_measure_id"]);

            $rx = D("RxCommon")->queryById($workorder["rx_id"]);
            $this->assign("rx", $rx);
        }

        //audit
        $audit0 = D("PrintTemplate")->queryById(33);
        $audit1 = D("PrintTemplate")->queryById(34);
        $audit2 = D("PrintTemplate")->queryById(35);
        $audit = D("Audit")->queryById($workorder["audit_id"]);
        $customizedProduct = D("CustomizedProduct")->where(array('customized_product_id'=>$audit["customized_product_id"]))->find();
        $this->assign("customized_product_name", $customizedProduct["customized_product_name"]);
        $process = D("Process")->queryById($workorder["process_id"]);

        $this->assign("workorder", $workorder);
        $this->assign("patientInfo", $patientInfo);
        $this->assign("examBasic", $examBasic);
        $this->assign("examBasicCP", $examBasicCP);
        $this->assign("examMeasure", $examMeasure);
        $this->assign("examAnalysis", $examAnalysis);
        $this->assign("examinator", $examinator);
        $this->assign("creator", $creator);
        $this->assign("sales", $sales);
        $this->assign("prescriber", $prescriber);
        $this->assign("reviewer", $reviewer);
        $this->assign("auditor", $auditor);
        $this->assign("page1", $page1);
        $this->assign("page2", $page2);
        $this->assign("order0", $order0);
        $this->assign("order1", $order1);
        $this->assign("order2", $order2);
        $this->assign("order3", $order3);
        $this->assign("order4", $order4);
        $this->assign("order5", $order5);
        $this->assign("order6", $order6);
        $this->assign("order7", $order7);
        $this->assign("order8", $order8);
        $this->assign("order9", $order9);
        $this->assign("audit0", $audit0);
        $this->assign("audit1", $audit1);
        $this->assign("audit2", $audit2);
        $this->assign("process", $process);
        $this->assign("audit", $audit);

        $this->display();

    }

    public function rx() {
        $rxId = $_REQUEST["rxId"];
        $id = $_REQUEST["id"];
        $hisId = $_REQUEST["hisId"];

        $workorder = D("Workorder")->queryById($id);

        if (isNullOrEmpty($rxId)) {
            $rxId = $workorder["rx_id"];
        }

        if($workorder["workorder_type"] == 1) {
            $this->currentModel = D("Rx");
            $map['class_name'] = array('like', array('rx', 'all'), 'or');
        }
        if($workorder["workorder_type"] == 2) {
            $this->currentModel = D("RxCommon");
            $map['class_name'] = array('like', array('rx_tlso', 'all'), 'or');
        }
        if($workorder["workorder_type"] == 4) {
            $this->currentModel = D("RxCommon");
            $map['class_name'] = array('like', array('rx_sco', 'all'), 'or');
            $examMeasure = D("ExamMeasureCommon")->queryById($workorder["exam_measure_id"]);
            $this->assign("examMeasure", $examMeasure);
        }
        if($workorder["workorder_type"] == 5 ||$workorder["workorder_type"] == 6) {
            $this->currentModel = D("RxCommon");
            $map['class_name'] = array('like', array('rxKafo', 'all'), 'or');
        }
        if($workorder["workorder_type"] == 7) {
            $this->currentModel = D("RxCommon");
            $map['class_name'] = array('like', array('rxFo', 'all'), 'or');
        }
        if($workorder["workorder_type"] == 8) {
            $this->currentModel = D("RxCommon");
            $map['class_name'] = array('like', array('rxThigh', 'all'), 'or');
        }
        if($workorder["workorder_type"] == 9) {
            $this->currentModel = D("RxCommon");
            $map['class_name'] = array('like', array('rxShank', 'all'), 'or');
        }

        if (!isNullOrEmpty($hisId)) {

            $rx = $this->currentModel->queryById($hisId);
            $rx["rx_id"] = $rxId;
        }else{
            $rx = $this->currentModel->queryById($rxId);
        }

        $formDict = D("FormDict")->queryForList($map);

//        $patientMap["patient_name"] = $patient["patient_name"];
//        $map["id_no"] = I("post.idNo");
//        $rxList = D("Rx")->queryForList(null,$patientMap);
        $patient = D("Patient")->queryById($workorder["patient_id"]);
        $workorder["patient_name"] = $patient["patient_name"];
        $hisRx = null;
        if(isNullOrEmpty($workorder["rx_id"]) && isNullOrEmpty($hisId)){
            $patient = D("Patient")->queryById($workorder["patient_id"]);
            $patientMap["patient_name"] = $patient["patient_name"];
            $patientMap["id_no"] = $patient["id_no"];

            $rxList = $this->currentModel->alias('r')
                ->join("left join __ADMIN__ a on a.employee_id = r.update_id")
                ->where($patientMap)
                ->order("r.create_time desc")
                ->field("r.*, a.admin_name")
                ->select();
            if(!isNullOrEmpty($rxList)){
                $hisRx = $rxList[0];
            }
        }

        $this->assign("rx", $rx);
        $this->assign("rxId", $rxId);
        $this->assign("hisRx", $hisRx);
        $this->assign("id", $id);
        $this->assign("workorder", $workorder);
        $this->assign("formDict", $formDict);
        if($workorder["workorder_type"] == 1) {
            $this->display("rx");
        }
        if($workorder["workorder_type"] == 2) {
            $this->display("rxTLSO");
        }
        if($workorder["workorder_type"] == 4) {
            $this->display("rxSCO");
        }
        if($workorder["workorder_type"] == 5 ||$workorder["workorder_type"] == 6) {
            $this->display("rxKAFO");
        }
        if($workorder["workorder_type"] == 7) {
            $this->display("rxFO");
        }
        if($workorder["workorder_type"] == 8) {
            $this->display("rxThigh");
        }
        if($workorder["workorder_type"] == 9) {
            $this->display("rxShank");
        }
    }

    function rx_post()
    {
        if (IS_POST) {

            $rxId = $_REQUEST["rxId"];
            $id = $_REQUEST["id"];
            $workorder = $this->currentModel->queryById($id);
//            if (isNullOrEmpty($rxId)) {
//                $rxId = $workorder["rx_id"];
//            }
            $patient = D("Patient")->queryById($workorder["patient_id"]);
            $users_obj= M("admin");
            $userId=$_SESSION['ADMIN_ID'];
            $user=$users_obj->where("user_id=$userId")->find();
            if (isNullOrEmpty($rxId)) {
                $rxId = D("Rx")->add(array(
                    'completed' => -1,
                    'version' => 2,
                    'create_time' => getCurrentDate(),
                    'update_time' => getCurrentDate(),
                    'update_id' => $user["employee_id"],
                    'patient_name' => $patient["patient_name"],
                    'id_no' => $patient["id_no"],
                    'side' => $workorder["side"],
                ));
                $workorder["rx_id"] = $rxId;
                D("Workorder")->updateInfo($workorder);
            }
            $rx = D("Rx")->queryById($rxId);

            $rx["combo"] = I('post.combo');

            $afotype_out_str = "";
            $afotype_out_ids = I('post.afotype_out_id');
            foreach ($afotype_out_ids as $afotype_id) {
                if($afotype_out_str == ""){
                    $afotype_out_str = $afotype_id;
                }else{
                    $afotype_out_str = $afotype_out_str . "," . $afotype_id;
                }
            }
            $rx["afotype_out"] = $afotype_out_str;

            //         if($rx["combo"] == "是"){
            $afotype_in_str = "";
            $afotype_in_ids = I('post.afotype_in_id');
            foreach ($afotype_in_ids as $afotype_id) {
                if($afotype_in_str == ""){
                    $afotype_in_str = $afotype_id;
                }else{
                    $afotype_in_str = $afotype_in_str . "," . $afotype_id;
                }
            }
            $rx["afotype_in"] = $afotype_in_str;
            $rx["afotype_in_note"] = I('post.afotype_in_note');
            //          }

            $rx["afotype_out_note"] = I('post.afotype_out_note');
            $rx["afotype_other_note"] = I('post.afotype_other_note');
            $rx["ahtype"] = I('post.ahtype');
            $rx["ahsize"] = I('post.ahsize');


//            $dorsal_sup_str = "";
//            $dorsal_sup_ids = I('post.dorsal_sup_id');
//            foreach ($dorsal_sup_ids as $dorsal_sup_id) {
//                if($dorsal_sup_str == ""){
//                    $dorsal_sup_str = $dorsal_sup_id;
//                }else{
//                    $dorsal_sup_str = $dorsal_sup_str . "," . $dorsal_sup_id;
//                }
//            }
//            $rx["dorsal_sup"] = $dorsal_sup_str;

            $rx["activity_limit"] = I('post.activity_limit');
            $rx["limit_level"] = I('post.limit_level');
            $rx["limit_level_angle"] = I('post.limit_level_angle');
            $rx["limit_level_other"] = I('post.limit_level_other');

            $flex_str = "";
            $flex_ids = I('post.flex_id');
            foreach ($flex_ids as $flex_id) {
                if($flex_str == ""){
                    $flex_str = $flex_id;
                }else{
                    $flex_str = $flex_str . "," . $flex_id;
                }
            }

            $rx["flex"] = $flex_str;
            $rx["flex_other"] = I('post.flex_other');
            $rx["sag_aa"] = I('post.sag_aa');
            $rx["sag_sva"] = I('post.sag_sva');
            $rx["heel"] = I('post.heel');
            $rx["heel_angle"] = I('post.heel_angle');
            $rx["forefoot"] = I('post.forefoot');
            $rx["outproduct"] = I('post.outproduct');
            $rx["out_pp"] = I('post.out_pp');
            $rx["out_carbpp"] = I('post.out_carbpp');
            $rx["out_copp"] = I('post.out_copp');
            $rx["out_pe"] = I('post.out_pe');
            $rx["out_enhpe"] = I('post.out_enhpe');
            $rx["out_dy"] = I('post.out_dy');

            //        if($rx["combo"] == "是") {
            $rx["inproduct"] = I('post.inproduct');
            $rx["in_dy"] = I('post.in_dy');
            $rx["in_enhpe"] = I('post.in_enhpe');
            $rx["in_copp"] = I('post.in_copp');
            $rx["in_pp"] = I('post.in_pp');
            $rx["in_eva"] = I('post.in_eva');
            $rx["innerproduct"] = I('post.innerproduct');
            $rx["inner_al"] = I('post.inner_al');
            $rx["inner_eva"] = I('post.inner_eva');
            $rx["inner_other"] = I('post.inner_other');
            //     }

            $mould_out_str = "";
            $mould_out_ids = I('post.mould_out_id');
            foreach ($mould_out_ids as $mould_out_id) {
                if($mould_out_str == ""){
                    $mould_out_str = $mould_out_id;
                }else{
                    $mould_out_str = $mould_out_str . "," . $mould_out_id;
                }
            }
            $rx["mould_out"] = $mould_out_str;

            $rx["mould_out_a"] = I('post.mould_out_a');
            $rx["mould_out_b"] = I('post.mould_out_b');
            $rx["mould_out_c"] = I('post.mould_out_c');
            $rx["mould_out_d"] = I('post.mould_out_d');
            $rx["mould_out_e"] = I('post.mould_out_e');
            $rx["mould_out_f"] = I('post.mould_out_f');
            $rx["mould_out_g"] = I('post.mould_out_g');
            $rx["mould_out_h"] = I('post.mould_out_h');
            $rx["mould_out_i"] = I('post.mould_out_i');

//            if($rx["combo"] == "是") {
//                $mould_in_str = "";
//                $mould_in_ids = I('post.mould_in_id');
//                foreach ($mould_in_ids as $mould_in_id) {
//                    if ($mould_in_str == "") {
//                        $mould_in_str = $mould_in_id;
//                    } else {
//                        $mould_in_str = $mould_in_str . "," . $mould_in_id;
//                    }
//                }
//                $rx["mould_in"] = $mould_in_str;
//
//                $rx["mould_in_a"] = I('post.mould_in_a');
//                $rx["mould_in_b"] = I('post.mould_in_b');
//                $rx["mould_in_c"] = I('post.mould_in_c');
//                $rx["mould_in_d"] = I('post.mould_in_d');
//                $rx["mould_in_e"] = I('post.mould_in_e');
//            }

            $rx["wedge_out_pos"] = I('post.wedge_out_pos');
            $rx["wedge_out_a"] = I('post.wedge_out_a');
            $rx["wedge_out_b"] = I('post.wedge_out_b');
            $rx["wedge_out_c"] = I('post.wedge_out_c');
            $rx["wedge_out_d"] = I('post.wedge_out_d');
            $rx["wedge_out_e"] = I('post.wedge_out_e');
            $rx["wedge_out_f"] = I('post.wedge_out_f');
            $rx["wedge_out_g"] = I('post.wedge_out_g');
            //        if($rx["combo"] == "是") {
            $rx["wedge_in_pos"] = I('post.wedge_in_pos');
            $rx["wedge_in_a"] = I('post.wedge_in_a');
            $rx["wedge_in_b"] = I('post.wedge_in_b');
            $rx["wedge_in_c"] = I('post.wedge_in_c');
            $rx["wedge_in_d"] = I('post.wedge_in_d');
            $rx["wedge_in_e"] = I('post.wedge_in_e');
            $rx["wedge_in_f"] = I('post.wedge_in_f');
            $rx["wedge_in_g"] = I('post.wedge_in_g');
            //        }

            $rx["sole_a"] = I('post.sole_a');
            $rx["sole_b"] = I('post.sole_b');
            $rx["sole_b_angle"] = I('post.sole_b_angle');
            $rx["sole_c"] = I('post.sole_c');
            $rx["sole_d"] = I('post.sole_d');
            $rx["hasp_out_len_a"] = I('post.hasp_out_len_a');
            $rx["hasp_out_type_a"] = I('post.hasp_out_type_a');
            $rx["hasp_out_start_a"] = I('post.hasp_out_start_a');
            $rx["hasp_out_side_a"] = I('post.hasp_out_side_a');
            $rx["hasp_out_start_a1"] = I('post.hasp_out_start_a1');
            $rx["hasp_out_side_a1"] = I('post.hasp_out_side_a1');
            $rx["hasp_out_tight_a"] = I('post.hasp_out_tight_a');
            $rx["hasp_out_other_a"] = I('post.hasp_out_other_a');
            $rx["hasp_out_len_b"] = I('post.hasp_out_len_b');
            $rx["hasp_out_type_b"] = I('post.hasp_out_type_b');
            $rx["hasp_out_start_b"] = I('post.hasp_out_start_b');
            $rx["hasp_out_side_b"] = I('post.hasp_out_side_b');
            $rx["hasp_out_start_b1"] = I('post.hasp_out_start_b1');
            $rx["hasp_out_side_b1"] = I('post.hasp_out_side_b1');
            $rx["hasp_out_tight_b"] = I('post.hasp_out_tight_b');
            $rx["hasp_out_other_b"] = I('post.hasp_out_other_b');
            $rx["hasp_out_len_c"] = I('post.hasp_out_len_c');
            $rx["hasp_out_type_c"] = I('post.hasp_out_type_c');
            $rx["hasp_out_start_c"] = I('post.hasp_out_start_c');
            $rx["hasp_out_side_c"] = I('post.hasp_out_side_c');
            $rx["hasp_out_start_c1"] = I('post.hasp_out_start_c1');
            $rx["hasp_out_side_c1"] = I('post.hasp_out_side_c1');
            $rx["hasp_out_cut_c"] = I('post.hasp_out_cut_c');
            $rx["hasp_out_tight_c"] = I('post.hasp_out_tight_c');
            $rx["hasp_out_other_c"] = I('post.hasp_out_other_c');
            $rx["hasp_out_len_d"] = I('post.hasp_out_len_d');
            $rx["hasp_out_type_d"] = I('post.hasp_out_type_d');
            $rx["hasp_out_start_d"] = I('post.hasp_out_start_d');
            $rx["hasp_out_side_d"] = I('post.hasp_out_side_d');
            $rx["hasp_out_start_d1"] = I('post.hasp_out_start_d1');
            $rx["hasp_out_side_d1"] = I('post.hasp_out_side_d1');
            $rx["hasp_out_tight_d"] = I('post.hasp_out_tight_d');
            $rx["hasp_out_other_d"] = I('post.hasp_out_other_d');

            //        if($rx["combo"] == "是") {
            $rx["hasp_in_len_a"] = I('post.hasp_in_len_a');
            $rx["hasp_in_type_a"] = I('post.hasp_in_type_a');
            $rx["hasp_in_start_a"] = I('post.hasp_in_start_a');
            $rx["hasp_in_side_a"] = I('post.hasp_in_side_a');
            $rx["hasp_in_start_a1"] = I('post.hasp_in_start_a1');
            $rx["hasp_in_side_a1"] = I('post.hasp_in_side_a1');
            $rx["hasp_in_tight_a"] = I('post.hasp_in_tight_a');
            $rx["hasp_in_other_a"] = I('post.hasp_in_other_a');
            $rx["hasp_in_len_b"] = I('post.hasp_in_len_b');
            $rx["hasp_in_type_b"] = I('post.hasp_in_type_b');
            $rx["hasp_in_start_b"] = I('post.hasp_in_start_b');
            $rx["hasp_in_side_b"] = I('post.hasp_in_side_b');
            $rx["hasp_in_start_b1"] = I('post.hasp_in_start_b1');
            $rx["hasp_in_side_b1"] = I('post.hasp_in_side_b1');
            $rx["hasp_in_tight_b"] = I('post.hasp_in_tight_b');
            $rx["hasp_in_other_b"] = I('post.hasp_in_other_b');
            $rx["hasp_in_len_c"] = I('post.hasp_in_len_c');
            $rx["hasp_in_type_c"] = I('post.hasp_in_type_c');
            $rx["hasp_in_start_c"] = I('post.hasp_in_start_c');
            $rx["hasp_in_side_c"] = I('post.hasp_in_side_c');
            $rx["hasp_in_start_c1"] = I('post.hasp_in_start_c1');
            $rx["hasp_in_side_c1"] = I('post.hasp_in_side_c1');
            $rx["hasp_in_cut_c"] = I('post.hasp_in_cut_c');
            $rx["hasp_in_tight_c"] = I('post.hasp_in_tight_c');
            $rx["hasp_in_other_c"] = I('post.hasp_in_other_c');
//                $rx["hasp_in_len_d"] = I('post.hasp_in_len_d');
//                $rx["hasp_in_type_d"] = I('post.hasp_in_type_d');
//                $rx["hasp_in_side_d"] = I('post.hasp_in_side_d');
//                $rx["hasp_in_tight_d"] = I('post.hasp_in_tight_d');
//                $rx["hasp_in_other_d"] = I('post.hasp_in_other_d');
            //          }

            $cutline_out_str = "";
            $cutline_out_ids = I('post.cutline_out_id');
            foreach ($cutline_out_ids as $cutline_out_id) {
                if($cutline_out_str == ""){
                    $cutline_out_str = $cutline_out_id;
                }else{
                    $cutline_out_str = $cutline_out_str . "," . $cutline_out_id;
                }
            }
            $rx["cutline_out"] = $cutline_out_str;
            $rx["cutline_out_other"] = I('post.cutline_out_other');
            $cutline_in_str = "";
            $cutline_in_ids = I('post.cutline_in_id');
            foreach ($cutline_in_ids as $cutline_in_id) {
                if($cutline_in_str == ""){
                    $cutline_in_str = $cutline_in_id;
                }else{
                    $cutline_in_str = $cutline_in_str . "," . $cutline_in_id;
                }
            }

            //       if($rx["combo"] == "是") {
            $rx["cutline_in"] = $cutline_in_str;
            $rx["cutline_in_other"] = I('post.cutline_in_other');
            //         }

            $pelma_out_str = "";
            $pelma_out_ids = I('post.pelma_out_id');
            foreach ($pelma_out_ids as $pelma_out_id) {
                if($pelma_out_str == ""){
                    $pelma_out_str = $pelma_out_id;
                }else{
                    $pelma_out_str = $pelma_out_str . "," . $pelma_out_id;
                }
            }
            $rx["pelma_out"] = $pelma_out_str;
            $rx["pelma_out_other"] = I('post.pelma_out_other');

            //       if($rx["combo"] == "是") {
            $pelma_in_str = "";
            $pelma_in_ids = I('post.pelma_in_id');
            foreach ($pelma_in_ids as $pelma_in_id) {
                if ($pelma_in_str == "") {
                    $pelma_in_str = $pelma_in_id;
                } else {
                    $pelma_in_str = $pelma_in_str . "," . $pelma_in_id;
                }
            }
            $rx["pelma_in"] = $pelma_in_str;
            $rx["pelma_in_other"] = I('post.pelma_in_other');
            //       }

            $rx["note"] = I('post.note');
            $rx["price"] = I('post.price');
            $rx["other_type"] = I('post.other_type');
            $rx["other_price"] = I('post.other_price');
            $rx["delivery_date"] = I("post.delivery_date");

            $rx["update_time"] = getCurrentDate();

            $rx["update_id"] = $user["employee_id"];

            if(I('post.completed') == "on"){
                $rx["completed"] = 1;
                $workorder["status"] = 3;
                $workorder["prescribe_time"] = getCurrentDate();
//                $workorder["price"] = I('post.price');
                $workorder["delivery_date"] = I("post.delivery_date");
                D("Workorder")->updateInfo($workorder);

                //推送留言信息到销售
                $patient = D("Patient")->queryById($workorder["patient_id"]);
                $sales = D("admin")->where(array('employee_id'=>$workorder["sales_id"]))->find();
                $creator = D("admin")->where(array('employee_id'=>$workorder["creator_id"]))->find();
                $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/workorder/index/id/" . $workorder["workorder_id"];
                $notifyData["first"] = "工单“".$workorder["workorder_no"]."”已经由：" . $user["admin_name"]."开处方，请临床部领料人申请领料；请制作人员开始制作。";
                $notifyData["keyword1"] = "患者：" . $patient["patient_name"] . " ".$workorder["side"]."，" . $patient["sex"] . "，" . $patient["age"] . "岁。[诊断--" . $patient["diagnosis"] . "]";
                $notifyData["keyword2"] = getCurrentDate();
                $notifyData["keyword3"] = "领料人、制作人员";
                $notifyData["remark"] = "下单人：" . $creator["admin_name"] . "，业务员：" . $sales["admin_name"] . "。处方人：" . $user["admin_name"];

//                $adminRoleArr = array("1","5");
//                $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
                $openidArray = getNotifyArrByName("prescribeWorkorder", $user["enterprise_code"]);
                array_push($openidArray, $sales["openid"]);
                $openidArray = array_unique($openidArray);
                foreach ($openidArray as $openid) {
                    $notifyData["openid"] = $openid;
                    WorkorderProcessingNotify($notifyData);
                }
            }

            D("Rx")->updateInfo($rx);
            $this->success("保存成功！", U("Workorder/index"));
        } else {
            $this->error("请为此用户指定角色！");
        }
    }

    function rx_tlso_post()
    {
        if (IS_POST) {

            $rxId = $_REQUEST["rxId"];
            $id = $_REQUEST["id"];
            $workorder = $this->currentModel->queryById($id);
//            if (isNullOrEmpty($rxId)) {
//                $rxId = $workorder["rx_id"];
//            }
            $patient = D("Patient")->queryById($workorder["patient_id"]);
            $users_obj= M("admin");
            $userId=$_SESSION['ADMIN_ID'];
            $user=$users_obj->where("user_id=$userId")->find();
            if (isNullOrEmpty($rxId)) {
                $rxId = D("RxCommon")->add(array(
                    'completed' => -1,
                    'version' => 2,
                    'workorder_type' => 2,
                    'create_time' => getCurrentDate(),
                    'update_time' => getCurrentDate(),
                    'update_id' => $user["employee_id"],
                    'patient_name' => $patient["patient_name"],
                    'id_no' => $patient["id_no"],
                ));
                $workorder["rx_id"] = $rxId;
                D("Workorder")->updateInfo($workorder);
            }
            $rx = D("RxCommon")->queryById($rxId);

            for($i = 0; $i < 88; $i++){
                $rx["rt".$i] = I("post.rt".$i);
            }

            $rx["rt0"] = str_replace(array("\r\n", "\r", "\n"), "。", $rx["rt0"]);
            if(!isNullOrEmpty($rx["rt0"])){
                $patient["diagnosis"] = $rx["rt0"];
                D("Patient")->updateInfo($patient);
            }
            $rx["rt1"] = str_replace(array("\r\n", "\r", "\n"), "。", $rx["rt1"]);
            $rx["note"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.note'));


            $mould_str = "";
            $mould_ids = I('post.mould_id');
            foreach ($mould_ids as $mould_id) {
                if($mould_str == ""){
                    $mould_str = $mould_id;
                }else{
                    $mould_str = $mould_str . "," . $mould_id;
                }
            }
            $rx["rt22"] = $mould_str;

            $rx["price"] = I('post.price');
            $rx["other_type"] = I('post.other_type');
            $rx["other_price"] = I('post.other_price');
            $rx["delivery_date"] = I("post.delivery_date");

            $rx["update_time"] = getCurrentDate();
            $rx["update_id"] = $user['employee_id'];

            if(I('post.completed') == "on"){
                $rx["completed"] = 1;
                $workorder["status"] = 3;
                $workorder["prescribe_time"] = getCurrentDate();
//                $workorder["price"] = I('post.price');
                $workorder["delivery_date"] = I("post.delivery_date");
                D("Workorder")->updateInfo($workorder);

                //推送留言信息到销售
                $sales = D("admin")->where(array('employee_id'=>$workorder["sales_id"]))->find();
                $creator = D("admin")->where(array('employee_id'=>$workorder["creator_id"]))->find();
                $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/workorder/index/id/" . $workorder["workorder_id"];
                $notifyData["first"] = "工单“".$workorder["workorder_no"]."”已经由：" . $user["admin_name"]."开处方，请临床部领料人申请领料；请制作人员开始制作。";
                $notifyData["keyword1"] = "患者：" . $patient["patient_name"] . " ".$workorder["side"]."，" . $patient["sex"] . "，" . $patient["age"] . "岁。[诊断--" . $patient["diagnosis"] . "]";
                $notifyData["keyword2"] = getCurrentDate();
                $notifyData["keyword3"] = "领料人、制作人员";
                $notifyData["remark"] = "下单人：" . $creator["admin_name"] . "，业务员：" . $sales["admin_name"] . "。处方人：" . $user["admin_name"];

//                $adminRoleArr = array("1","5");
//                $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
                $openidArray = getNotifyArrByName("prescribeWorkorder", $user["enterprise_code"]);
                array_push($openidArray, $sales["openid"]);
                $openidArray = array_unique($openidArray);
                foreach ($openidArray as $openid) {
                    $notifyData["openid"] = $openid;
                    WorkorderProcessingNotify($notifyData);
                }
            }

            D("RxCommon")->updateInfo($rx);
            $this->success("保存成功！", U("Workorder/index"));
        } else {
            $this->error("请为此用户指定角色！");
        }
    }

    function rx_sco_post()
    {
        if (IS_POST) {

            $rxId = $_REQUEST["rxId"];
            $id = $_REQUEST["id"];
            $workorder = D("Workorder")->queryById($id);
//            if (isNullOrEmpty($rxId)) {
//                $rxId = $workorder["rx_id"];
//            }
            $patient = D("Patient")->queryById($workorder["patient_id"]);
            $users_obj= M("admin");
            $userId=$_SESSION['ADMIN_ID'];
            $user=$users_obj->where("user_id=$userId")->find();
            if (isNullOrEmpty($rxId)) {
                $rxId = D("RxCommon")->add(array(
                    'completed' => -1,
                    'version' => 2,
                    'workorder_type' => $workorder["workorder_type"],
                    'create_time' => getCurrentDate(),
                    'update_time' => getCurrentDate(),
                    'update_id' => $user["employee_id"],
                    'patient_name' => $patient["patient_name"],
                    'id_no' => $patient["id_no"],
                ));
                $workorder["rx_id"] = $rxId;
                D("Workorder")->updateInfo($workorder);
            }
            $rx = D("RxCommon")->queryById($rxId);

            $step1_str = "";
            $step1_ids = I('post.step1_id');
            foreach ($step1_ids as $step1_id) {
                if($step1_str == ""){
                    $step1_str = $step1_id;
                }else{
                    $step1_str .= "," . $step1_id;
                }
            }
            $rx["rt0"] = $step1_str;

            $step2_str = "";
            $step2_ids = I('post.step2_id');
            foreach ($step2_ids as $step2_id) {
                if($step2_str == ""){
                    $step2_str = $step2_id;
                }else{
                    $step2_str .= "," . $step2_id;
                }
            }

            $step1 = (int)$step1_str + 1;
            for($i = 1; $i < 5; ++$i) {
                if($i == $step1){
                    $rx["rt".$i] = $step2_str;
                }else{
                    $rx["rt".$i] = "";
                }
            }

            for($i = 5; $i <= 34; $i++){
                $rx["rt".$i] = I("post.rt".$i);
            }
            $rx["long0"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.long0'));
            $rx["long1"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.long1'));
            $rx["long2"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.long2'));
            $rx["note"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.note'));
            $rx["price"] = I('post.price');
            $rx["other_type"] = I('post.other_type');
            $rx["other_price"] = I('post.other_price');
            $rx["delivery_date"] = I("post.delivery_date");

            $rx["update_time"] = getCurrentDate();
            $rx["update_id"] = $user['employee_id'];

            if(I('post.completed') == "on"){
                $rx["completed"] = 1;
                $workorder["status"] = 3;
                $workorder["prescribe_time"] = getCurrentDate();
//                $workorder["price"] = I('post.price');
                $workorder["delivery_date"] = I("post.delivery_date");
                D("Workorder")->updateInfo($workorder);

                //推送留言信息到销售
                $sales = D("admin")->where(array('employee_id'=>$workorder["sales_id"]))->find();
                $creator = D("admin")->where(array('employee_id'=>$workorder["creator_id"]))->find();
                $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/workorder/index/id/" . $workorder["workorder_id"];
                $notifyData["first"] = "工单“".$workorder["workorder_no"]."”已经由：" . $user["admin_name"]."开处方，请临床部领料人申请领料；请制作人员开始制作。";
                $notifyData["keyword1"] = "患者：" . $patient["patient_name"] . " ".$workorder["side"]."，" . $patient["sex"] . "，" . $patient["age"] . "岁。[诊断--" . $patient["diagnosis"] . "]";
                $notifyData["keyword2"] = getCurrentDate();
                $notifyData["keyword3"] = "领料人、制作人员";
                $notifyData["remark"] = "下单人：" . $creator["admin_name"] . "，业务员：" . $sales["admin_name"] . "。处方人：" . $user["admin_name"];

//                $adminRoleArr = array("1","5");
//                $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
                $openidArray = getNotifyArrByName("prescribeWorkorder", $user["enterprise_code"]);
                array_push($openidArray, $sales["openid"]);
                $openidArray = array_unique($openidArray);
                foreach ($openidArray as $openid) {
                    $notifyData["openid"] = $openid;
                    WorkorderProcessingNotify($notifyData);
                }
            }

            D("RxCommon")->updateInfo($rx);
            $this->success("保存成功！", U("Workorder/index"));
        } else {
            $this->error("请为此用户指定角色！");
        }
    }

    function rx_kafo_post()
    {
        if (IS_POST) {

            $rxId = $_REQUEST["rxId"];
            $id = $_REQUEST["id"];
            $workorder = D("Workorder")->queryById($id);
//            if (isNullOrEmpty($rxId)) {
//                $rxId = $workorder["rx_id"];
//            }
            $patient = D("Patient")->queryById($workorder["patient_id"]);
            $users_obj= M("admin");
            $userId=$_SESSION['ADMIN_ID'];
            $user=$users_obj->where("user_id=$userId")->find();
            if (isNullOrEmpty($rxId)) {
                $rxId = D("RxCommon")->add(array(
                    'completed' => -1,
                    'version' => 2,
                    'workorder_type' => $workorder["workorder_type"],
                    'create_time' => getCurrentDate(),
                    'update_time' => getCurrentDate(),
                    'update_id' => $user["employee_id"],
                    'patient_name' => $patient["patient_name"],
                    'id_no' => $patient["id_no"],
                ));
                $workorder["rx_id"] = $rxId;
                D("Workorder")->updateInfo($workorder);
            }
            $rx = D("RxCommon")->queryById($rxId);

            for($i = 0; $i <= 21; $i++){
                $rx["rt".$i] = I("post.rt".$i);
            }
            $rx["long0"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.long0'));
            $rx["long1"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.long1'));
            $rx["long2"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.long2'));
            $rx["note"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.note'));
            $rx["adapt"] = I('post.adapt');
            $rx["price"] = I('post.price');
            $rx["other_type"] = I('post.other_type');
            $rx["other_price"] = I('post.other_price');
            $rx["delivery_date"] = I("post.delivery_date");

            $rx["update_time"] = getCurrentDate();
            $rx["update_id"] = $user['employee_id'];

            if(I('post.completed') == "on"){
                $rx["completed"] = 1;
                if($rx["rt0"] == "HKAFO"){
                    $workorder["customized_product_id"] = 7;
                }
                $workorder["status"] = 3;
                $workorder["prescribe_time"] = getCurrentDate();
//                $workorder["price"] = I('post.price');
                $workorder["delivery_date"] = I("post.delivery_date");
                D("Workorder")->updateInfo($workorder);

                //推送留言信息到销售
                $sales = D("admin")->where(array('employee_id'=>$workorder["sales_id"]))->find();
                $creator = D("admin")->where(array('employee_id'=>$workorder["creator_id"]))->find();
                $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/workorder/index/id/" . $workorder["workorder_id"];
                $notifyData["first"] = "工单“".$workorder["workorder_no"]."”已经由：" . $user["admin_name"]."开处方，请临床部领料人申请领料；请制作人员开始制作。";
                $notifyData["keyword1"] = "患者：" . $patient["patient_name"] . " ".$workorder["side"]."，" . $patient["sex"] . "，" . $patient["age"] . "岁。[诊断--" . $patient["diagnosis"] . "]";
                $notifyData["keyword2"] = getCurrentDate();
                $notifyData["keyword3"] = "领料人、制作人员";
                $notifyData["remark"] = "下单人：" . $creator["admin_name"] . "，业务员：" . $sales["admin_name"] . "。处方人：" . $user["admin_name"];

//                $adminRoleArr = array("1","5");
//                $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
                $openidArray = getNotifyArrByName("prescribeWorkorder", $user["enterprise_code"]);
                array_push($openidArray, $sales["openid"]);
                $openidArray = array_unique($openidArray);
                foreach ($openidArray as $openid) {
                    $notifyData["openid"] = $openid;
                    WorkorderProcessingNotify($notifyData);
                }
            }

            D("RxCommon")->updateInfo($rx);
            $this->success("保存成功！", U("Workorder/index"));
        } else {
            $this->error("请为此用户指定角色！");
        }
    }

    function rx_fo_post()
    {
        if (IS_POST) {

            $rxId = $_REQUEST["rxId"];
            $id = $_REQUEST["id"];
            $workorder = D("Workorder")->queryById($id);
//            if (isNullOrEmpty($rxId)) {
//                $rxId = $workorder["rx_id"];
//            }
            $patient = D("Patient")->queryById($workorder["patient_id"]);
            $users_obj= M("admin");
            $userId=$_SESSION['ADMIN_ID'];
            $user=$users_obj->where("user_id=$userId")->find();
            if (isNullOrEmpty($rxId)) {
                $rxId = D("RxCommon")->add(array(
                    'completed' => -1,
                    'version' => 2,
                    'workorder_type' => $workorder["workorder_type"],
                    'create_time' => getCurrentDate(),
                    'update_time' => getCurrentDate(),
                    'update_id' => $user["employee_id"],
                    'patient_name' => $patient["patient_name"],
                    'id_no' => $patient["id_no"],
                ));
                $workorder["rx_id"] = $rxId;
                D("Workorder")->updateInfo($workorder);
            }
            $rx = D("RxCommon")->queryById($rxId);

            for($i = 0; $i <= 8; $i++){
                $rx["rt".$i] = I("post.rt".$i);
            }
            $rx["long0"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.long0'));
            $rx["long1"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.long1'));
            $rx["long2"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.long2'));
            $rx["note"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.note'));
            $rx["adapt"] = I('post.adapt');
            $rx["price"] = I('post.price');
            $rx["other_type"] = I('post.other_type');
            $rx["other_price"] = I('post.other_price');
            $rx["delivery_date"] = I("post.delivery_date");

            $rx["update_time"] = getCurrentDate();
            $rx["update_id"] = $user['employee_id'];

            if(I('post.completed') == "on"){
                $rx["completed"] = 1;
                if($rx["rt0"] == "HKAFO"){
                    $workorder["customized_product_id"] = 7;
                }
                $workorder["status"] = 3;
                $workorder["prescribe_time"] = getCurrentDate();
//                $workorder["price"] = I('post.price');
                $workorder["delivery_date"] = I("post.delivery_date");
                D("Workorder")->updateInfo($workorder);

                //推送留言信息到销售
                $sales = D("admin")->where(array('employee_id'=>$workorder["sales_id"]))->find();
                $creator = D("admin")->where(array('employee_id'=>$workorder["creator_id"]))->find();
                $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/workorder/index/id/" . $workorder["workorder_id"];
                $notifyData["first"] = "工单“".$workorder["workorder_no"]."”已经由：" . $user["admin_name"]."开处方，请临床部领料人申请领料；请制作人员开始制作。";
                $notifyData["keyword1"] = "患者：" . $patient["patient_name"] . " ".$workorder["side"]."，" . $patient["sex"] . "，" . $patient["age"] . "岁。[诊断--" . $patient["diagnosis"] . "]";
                $notifyData["keyword2"] = getCurrentDate();
                $notifyData["keyword3"] = "领料人、制作人员";
                $notifyData["remark"] = "下单人：" . $creator["admin_name"] . "，业务员：" . $sales["admin_name"] . "。处方人：" . $user["admin_name"];

//                $adminRoleArr = array("1","5");
//                $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
                $openidArray = getNotifyArrByName("prescribeWorkorder", $user["enterprise_code"]);
                array_push($openidArray, $sales["openid"]);
                $openidArray = array_unique($openidArray);
                foreach ($openidArray as $openid) {
                    $notifyData["openid"] = $openid;
                    WorkorderProcessingNotify($notifyData);
                }
            }

            D("RxCommon")->updateInfo($rx);
            $this->success("保存成功！", U("Workorder/index"));
        } else {
            $this->error("请为此用户指定角色！");
        }
    }

    function rx_thigh_post()
    {
        if (IS_POST) {

            $rxId = $_REQUEST["rxId"];
            $id = $_REQUEST["id"];
            $workorder = D("Workorder")->queryById($id);
//            if (isNullOrEmpty($rxId)) {
//                $rxId = $workorder["rx_id"];
//            }
            $patient = D("Patient")->queryById($workorder["patient_id"]);
            $users_obj= M("admin");
            $userId=$_SESSION['ADMIN_ID'];
            $user=$users_obj->where("user_id=$userId")->find();
            if (isNullOrEmpty($rxId)) {
                $rxId = D("RxCommon")->add(array(
                    'completed' => -1,
                    'version' => 2,
                    'workorder_type' => $workorder["workorder_type"],
                    'create_time' => getCurrentDate(),
                    'update_time' => getCurrentDate(),
                    'update_id' => $user["employee_id"],
                    'patient_name' => $patient["patient_name"],
                    'id_no' => $patient["id_no"],
                ));
                $workorder["rx_id"] = $rxId;
                D("Workorder")->updateInfo($workorder);
            }
            $rx = D("RxCommon")->queryById($rxId);

            for($i = 0; $i <= 21; $i++){
                $rx["rt".$i] = I("post.rt".$i);
            }
            $rx["long0"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.long0'));
            $rx["long1"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.long1'));
            $rx["long2"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.long2'));
            $rx["note"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.note'));
            $rx["adapt"] = I('post.adapt');
            $rx["price"] = I('post.price');
            $rx["other_type"] = I('post.other_type');
            $rx["other_price"] = I('post.other_price');
            $rx["delivery_date"] = I("post.delivery_date");

            $rx["update_time"] = getCurrentDate();
            $rx["update_id"] = $user['employee_id'];

            if(I('post.completed') == "on"){
                $rx["completed"] = 1;
                if($rx["rt0"] == "HKAFO"){
                    $workorder["customized_product_id"] = 7;
                }
                $workorder["status"] = 3;
                $workorder["prescribe_time"] = getCurrentDate();
//                $workorder["price"] = I('post.price');
                $workorder["delivery_date"] = I("post.delivery_date");
                D("Workorder")->updateInfo($workorder);

                //推送留言信息到销售
                $sales = D("admin")->where(array('employee_id'=>$workorder["sales_id"]))->find();
                $creator = D("admin")->where(array('employee_id'=>$workorder["creator_id"]))->find();
                $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/workorder/index/id/" . $workorder["workorder_id"];
                $notifyData["first"] = "工单“".$workorder["workorder_no"]."”已经由：" . $user["admin_name"]."开处方，请临床部领料人申请领料；请制作人员开始制作。";
                $notifyData["keyword1"] = "患者：" . $patient["patient_name"] . " ".$workorder["side"]."，" . $patient["sex"] . "，" . $patient["age"] . "岁。[诊断--" . $patient["diagnosis"] . "]";
                $notifyData["keyword2"] = getCurrentDate();
                $notifyData["keyword3"] = "领料人、制作人员";
                $notifyData["remark"] = "下单人：" . $creator["admin_name"] . "，业务员：" . $sales["admin_name"] . "。处方人：" . $user["admin_name"];

//                $adminRoleArr = array("1","5");
//                $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
                $openidArray = getNotifyArrByName("prescribeWorkorder", $user["enterprise_code"]);
                array_push($openidArray, $sales["openid"]);
                $openidArray = array_unique($openidArray);
                foreach ($openidArray as $openid) {
                    $notifyData["openid"] = $openid;
                    WorkorderProcessingNotify($notifyData);
                }
            }

            D("RxCommon")->updateInfo($rx);
            $this->success("保存成功！", U("Workorder/index"));
        } else {
            $this->error("请为此用户指定角色！");
        }
    }

    public function process() {
        $processId = $_REQUEST["processId"];
        $id = $_REQUEST["id"];

        $workorder = $this->currentModel->queryById($id);

        if (isNullOrEmpty($processId)) {
            $processId = $workorder["process_id"];
        }
        if (isNullOrEmpty($processId)) {
            $processId = D("Process")->add(array(
                'status' => '0,0,0,0,0,0,0,0,0,0,0,0,0,0',
                'version' => 2,
                'update_time' => getCurrentDate(),
            ));
            $workorder["process_id"] = $processId;
            $workorder["process_status"] = '0,0,0,0,0,0,0,0,0,0,0,0,0,0';
            D("Workorder")->updateInfo($workorder);
        }
        $process = D("Process")->queryById($processId);

        $patient = D("Patient")->queryById($workorder["patient_id"]);
        $sales = D("admin")->where(array('employee_id'=>$workorder["sales_id"]))->find();
        $prescriber = D("admin")->where(array('employee_id'=>$workorder["prescriber_id"]))->find();

        $cpList = D("CustomizedProduct")->select();
        $this->assign("cpList", $cpList);

        $instore = D("Instore")->where(array("product_id"=>$workorder["workorder_id"]))->find();
        $this->assign("instore", $instore);
        $this->assign("process", $process);
        $this->assign("processId", $processId);
        $this->assign("id", $id);
        $this->assign("patient", $patient);
        $this->assign("sales", $sales);
        $this->assign("prescriber", $prescriber);
        $this->assign("workorder", $workorder);

        $page = $_REQUEST["page"];
        $statusArr=explode(",",$process["status"]);
        $pageStatus = 1;
        if(isNullOrEmpty($page))
        {
            for($i = 0; $i < 12; $i++){
                if($statusArr[$i] != "1"){
                    $page = $i+1;
                    $pageStatus = 0;
                    break;
                }
            }
        }else{
            if($statusArr[$page - 1] != "1"){
                $pageStatus = 0;
            }
        }
        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();
        if(in_role(array("1"),$user['role'])){
            $this->assign("adminUpdate", "true");
        }
        $this->assign("user", $user);
        $this->assign("page", $page);
        $this->assign("home", $_REQUEST["home"]);
        $this->assign("pageStatus", $pageStatus);

        $enterprise=D("Enterprise")->where(array('enterprise_code'=>$user["enterprise_code"]))->find();
        $orthosisProcess = explode(',',$enterprise["orthosis_process"]);
        $this->assign('orthosisProcess', $orthosisProcess);

        $this->display("process".$page);
    }

    function process_post()
    {
        if (IS_POST) {

            $processId = $_REQUEST["processId"];
            $id = $_REQUEST["id"];
            $workorder = $this->currentModel->queryById($id);
            if (isNullOrEmpty($processId)) {
                $processId = $workorder["process_id"];
            }

            $process = D("Process")->queryById($processId);
            $users_obj= M("admin");
            $userId=$_SESSION['ADMIN_ID'];
            $user=$users_obj->where("user_id=$userId")->find();
            $signImage = $user["signimgurl"];
            switch (I('post.pageId')) {
                case 1:
                    $process["p1"] = I('post.p1');
                    $process["p2"] = I('post.p2');
                    $process["p3"] = I('post.p3');
                    $process["p4"] = I('post.p4');
                    $process["p5"] = I('post.p5');
                    $process["p6"] = I('post.p6');
                    $process["p7"] = I('post.p7');
                    $process["p8"] = I('post.p8');
                    if(isNullOrEmpty($signImage))
                        $process["p9"] = $user["admin_name"];
                    else
                        $process["p9"] = $signImage;
                    $process["p10"] = I('post.p10');
                    $process["p11"] = I('post.p11');
                    $processName = "取阴模";
                    break;
                case 2:
                    $process["p12"] = I('post.p12');
                    $process["p13"] = I('post.p13');
                    $process["p14"] = I('post.p14');
                    $process["p15"] = I('post.p15');
                    $process["p16"] = I('post.p16');
                    $process["p17"] = I('post.p17');
                    $process["p18"] = I('post.p18');
                    $process["p19"] = I('post.p19');
                    $process["p20"] = I('post.p20');
                    $process["p21"] = I('post.p21');
                    $process["p22"] = I('post.p22');
                    $process["p23"] = I('post.p23');
                    $process["p24"] = I('post.p24');
                    $process["p25"] = I('post.p25');
                    $process["p26"] = I('post.p26');
                    $process["p27"] = I('post.p27');
                    if(isNullOrEmpty($signImage))
                        $process["p28"] = $user["admin_name"];
                    else
                        $process["p28"] = $signImage;
                    $processName = "检查取阴模";
                    break;
                case 3:
                    $process["p29"] = I('post.p29');
                    $process["p30"] = I('post.p30');
                    $process["p31"] = I('post.p31');
                    $process["p32"] = I('post.p32');
                    $process["p33"] = I('post.p33');
                    $process["p34"] = I('post.p34');
                    if(isNullOrEmpty($signImage))
                        $process["p35"] = $user["admin_name"];
                    else
                        $process["p35"] = $signImage;
                    $process["p36"] = I('post.p36');
                    $process["p37"] = I('post.p37');
                    $processName = "修阳模";
                    break;
                case 4:
                    $process["p38"] = I('post.p38');
                    $process["p39"] = I('post.p39');
                    $process["p40"] = I('post.p40');
                    $process["p41"] = I('post.p41');
                    $process["p42"] = I('post.p42');
                    $process["p43"] = I('post.p43');
                    $process["p44"] = I('post.p44');
                    $process["p45"] = I('post.p45');
                    $process["p46"] = I('post.p46');
                    $process["p47"] = I('post.p47');
                    $process["p48"] = I('post.p48');
                    $process["p49"] = I('post.p49');
                    $process["p50"] = I('post.p50');
                    $process["p51"] = I('post.p51');
                    $process["p52"] = I('post.p52');
                    $process["p53"] = I('post.p53');
                    $process["p54"] = I('post.p54');
                    $process["p60"] = I('post.p60');
                    if(isNullOrEmpty($signImage))
                        $process["p61"] = $user["admin_name"];
                    else
                        $process["p61"] = $signImage;
                    $processName = "检查修阳模";
                    break;
                case 5:
                    $process["p55"] = I('post.p55');
                    $process["p56"] = I('post.p56');
                    $process["p57"] = I('post.p57');
                    $process["p58"] = I('post.p58');
                    $process["p62"] = I('post.p62');
                    $process["p63"] = I('post.p63');
                    $process["p64"] = I('post.p64');
                    $process["p65"] = I('post.p65');
                    $process["p66"] = I('post.p66');
                    $process["p67"] = I('post.p67');
                    $process["p68"] = I('post.p68');
                    $process["p69"] = I('post.p69');
                    $process["p70"] = I('post.p70');
                    $process["p71"] = I('post.p71');
                    $process["p72"] = I('post.p72');
                    $process["p73"] = I('post.p73');
                    $process["p74"] = I('post.p74');
                    $process["p75"] = I('post.p75');
                    $process["p76"] = I('post.p76');
                    $process["p77"] = I('post.p77');
                    $process["p78"] = I('post.p78');
                    $process["p79"] = I('post.p79');
                    $process["p80"] = I('post.p80');
                    $process["p81"] = I('post.p81');
                    $process["p82"] = I('post.p82');
                    $process["p83"] = I('post.p83');
                    $process["p84"] = I('post.p84');
                    if(isNullOrEmpty($signImage))
                        $process["p85"] = $user["admin_name"];
                    else
                        $process["p85"] = $signImage;
                    $process["p86"] = I('post.p86');
                    $process["p87"] = I('post.p87');
                    $processName = "热塑成型";
                    break;
                case 6:
                    $process["p88"] = I('post.p88');
                    $process["p89"] = I('post.p89');
                    $process["p90"] = I('post.p90');
                    $process["p91"] = I('post.p91');
                    $process["p92"] = I('post.p92');
                    if(isNullOrEmpty($signImage))
                        $process["p93"] = $user["admin_name"];
                    else
                        $process["p93"] = $signImage;
                    $processName = "检查热塑成型";
                    break;
                case 7:
                    $process["p94"] = I('post.p94');
                    $process["p95"] = I('post.p95');
                    $process["p96"] = I('post.p96');
                    $process["p97"] = I('post.p97');
                    $process["p98"] = I('post.p98');
                    $process["p99"] = I('post.p99');
                    $process["p100"] = I('post.p100');
                    $process["p101"] = I('post.p101');
                    $process["p102"] = I('post.p102');
                    if(isNullOrEmpty($signImage))
                        $process["p103"] = $user["admin_name"];
                    else
                        $process["p103"] = $signImage;
                    $process["p104"] = I('post.p104');
                    $process["p105"] = I('post.p105');
                    $processName = "打磨抛光";
                    break;
                case 8:
                    $process["p106"] = I('post.p106');
                    $process["p107"] = I('post.p107');
                    $process["p108"] = I('post.p108');
                    if(isNullOrEmpty($signImage))
                        $process["p109"] = $user["admin_name"];
                    else
                        $process["p109"] = $signImage;
                    $processName = "检查打磨抛光";
                    break;
                case 9:
                    $process["p110"] = I('post.p110');
                    $process["p111"] = I('post.p111');
                    $process["p112"] = I('post.p112');
                    if(isNullOrEmpty($signImage))
                        $process["p113"] = $user["admin_name"];
                    else
                        $process["p113"] = $signImage;
                    $process["p114"] = I('post.p114');
                    $process["p115"] = I('post.p115');
                    $processName = "组装对线";
                    break;
                case 10:
                    $process["p116"] = I('post.p116');
                    $process["p117"] = I('post.p117');
                    if(isNullOrEmpty($signImage))
                        $process["p118"] = $user["admin_name"];
                    else
                        $process["p118"] = $signImage;
                    $process["p119"] = I('post.p119');
                    $process["p120"] = I('post.p120');
                    $processName = "半成品适配";
                    break;
                case 11:
                    $process["p121"] = I('post.p121');
                    if(isNullOrEmpty($signImage))
                        $process["p122"] = $user["admin_name"];
                    else
                        $process["p122"] = $signImage;
                    $process["p123"] = I('post.p123');
                    $process["p124"] = I('post.p124');
                    $processName = "穿戴及使用训练";
                    break;
                case 12:
                    $process["p125"] = I('post.production_date');
                    $process["p126"] = I('post.storage_time');
//                    $workorder["batch_no"] = I('post.batch_no');
                    $workorder["storage_time"] = I('post.storage_time');
                    if(isNullOrEmpty($signImage))
                        $process["p127"] = $user["admin_name"];
                    else
                        $process["p127"] = $signImage;
                    $processName = "入库";
                    if(I('post.completed') == "on"){
                        $workorder["status"] = 4;
                        $workorder["storeman_id"] = $user["employee_id"];
                        $instoreId = D("Instore")->add(array(
                            'status' => 1,
                            'instore_type' => 1,
                            'code_id' => I('post.code_id'),
                            'inventory_name' => I('post.name'),
                            'spec' => I('post.spec'),
                            'number' => I('post.number'),
                            'unit' => I('post.unit'),
                            'barcode' => I('post.barcode'),
                            'store_id' => I('post.store_id'),
                            'note' => I('post.note'),
                            'production_date' => I('post.production_date'),
                            'expiry_date' => I('post.expiry_date'),
                            'storage_time' => I('post.storage_time'),
                            'update_id' => $user["employee_id"],
                            'create_time' => getCurrentDate(),
                            'update_time' => getCurrentDate(),
                            'product_id' => $workorder["workorder_id"],
                            'enterprise_code' => $user["enterprise_code"],
                            'outstore_status' => -1,
                        ));

                        $storageId = D("Storage")->add(array(
                            'type' => '定制矫形器',
                            'instore_id' => $instoreId,
                            'store_id' => I('post.store_id'),
                            'price' => $workorder["price"] ,
                            'storage_number' => I('post.number'),
                            'production_date' => I('post.production_date'),
                            'expiry_date' => I('post.expiry_date'),
                            'update_id' => $user["employee_id"],
                            'update_time' => getCurrentDate(),
                            'product_id' => $workorder["workorder_id"],
                            'enterprise_code' => $user["enterprise_code"],
                        ));

                        //推送完成信息
                        $patient = D("Patient")->queryById($workorder["patient_id"]);
                        $sales = D("admin")->where(array('employee_id'=>$workorder["sales_id"]))->find();
                        $prescriber = D("admin")->where(array('employee_id'=>$workorder["prescriber_id"]))->find();
                        $creator = D("admin")->where(array('employee_id'=>$workorder["creator_id"]))->find();
                        $examinator = D("admin")->where(array('employee_id'=>$workorder["examinator_id"]))->find();
                        $store = D("Store")->where(array('store_id'=>I('post.store_id')))->find();
                        $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/workorder/index/id/" . $workorder["workorder_id"];
                        $notifyData["first"] = "工单“".$workorder["workorder_no"]."”已经由 ".$user["admin_name"]." 完成出库。";
                        $notifyData["keyword1"] = "患者：" . $patient["patient_name"] . " ".$workorder["side"]."，" . $patient["sex"] . "，" . $patient["age"] . "岁。[诊断--" . $patient["diagnosis"] . "]";
                        $notifyData["keyword2"] = $store["store_name"];
                        $notifyData["keyword3"] = $workorder["update_time"] . "（下单时间）";
                        $notifyData["keyword4"] = $workorder["storage_time"]. "（入库时间）";
                        $notifyData["keyword5"] = "下单人：" . $creator["admin_name"] . "，检查测量人：" . $examinator["admin_name"]."，业务员：" . $sales["admin_name"] . "，处方人：" . $prescriber["admin_name"];
                        $notifyData["remark"] = "矫形器种类：" . $workorder["type_name"] ."，订单价格：" . $workorder["price"];
//                        $adminRoleArr = array("1", "3");
//                        $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
                        $openidArray = getNotifyArrByName("endWorkorder", $user["enterprise_code"]);
                        array_push($openidArray, $user["openid"]);
                        array_push($openidArray, $sales["openid"]);
                        $openidArray = array_unique($openidArray);
                        foreach ($openidArray as $openid) {
                            $notifyData["openid"] = $openid;
                            workorderEndNotify($notifyData);
                        }
                    }
                    break;
            }

            if(I('post.completed') == "on"){
                $pageIndex = I('post.pageId') - 1;

                $statusArr = explode(",", $process["status"]);
                $statusArr[$pageIndex] = "1";
                $enterprise=D("Enterprise")->where(array('enterprise_code'=>$user["enterprise_code"]))->find();
                $orthosisProcess = explode(',',$enterprise["orthosis_process"]);
                $finished = true;
                $i = 0;
                foreach ($statusArr as $statusValue) {
                    if ($i == 0) {
                        $process["status"] = $statusValue;
                    } else {
                        $process["status"] .= "," . $statusValue;
                    }

                    if ($i < 10 && $statusValue != $orthosisProcess[$i]) {
                        $finished = false;
                    }
                    $i++;
                }

                $workorder["process_status"] = $process["status"];
                D("Workorder")->updateInfo($workorder);
                $process["update_time"] = getCurrentDate();
                $process["update_id"] = $user["employee_id"];
                if($finished == true && $pageIndex < 10) {
                    //推送留言信息到质检人员
                    $patient = D("Patient")->queryById($workorder["patient_id"]);
                    $sales = D("admin")->where(array('employee_id'=>$workorder["sales_id"]))->find();
                    $prescriber = D("admin")->where(array('employee_id'=>$workorder["prescriber_id"]))->find();
                    $creator = D("admin")->where(array('employee_id'=>$workorder["creator_id"]))->find();
                    $users_obj= M("admin");
                    $userId=$_SESSION['ADMIN_ID'];
                    $user=$users_obj->where("user_id=$userId")->find();

                    $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/workorder/index/id/" . $workorder["workorder_id"];
                    $notifyData["first"] = "工单“".$workorder["workorder_no"]."”已经完成审批记录，请质检人进行检查。";
                    $notifyData["keyword1"] = "患者：" . $patient["patient_name"] . " ".$workorder["side"]."，" . $patient["sex"] . "，" . $patient["age"] . "岁。[诊断--" . $patient["diagnosis"] . "]";
                    $notifyData["keyword2"] = getCurrentDate();
                    $notifyData["keyword3"] = "质检人";
                    $notifyData["remark"] = "下单人：" . $creator["admin_name"] . "，业务员：" . $sales["admin_name"] . "。处方人：" . $prescriber["admin_name"];

//                    $adminRoleArr = array("1","9");
//                    $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
                    $openidArray = getNotifyArrByName("processEndWorkorder", $user["enterprise_code"]);
                    $openidArray = array_unique($openidArray);
                    foreach ($openidArray as $openid) {
                        $notifyData["openid"] = $openid;
                        WorkorderProcessingNotify($notifyData);
                    }
                }
            }
            try{
                D("Process")->updateInfo($process);
            }
            catch(Exception $e){
                $this->error("数据库异常：".$e->getMessage());
            }

//            if(I('post.home') == 1){
//                $this->success("保存成功！", U("Workorder/home"));
//            }else{
                $this->success("保存成功！", U("Workorder/index"));
//            }
        } else {
            $this->error("请为此用户指定角色！");
        }
    }

    public function audit() {
        $id = $_REQUEST["id"];
        $workorder = $this->currentModel->queryById($id);

        $patient = D("Patient")->queryById($workorder["patient_id"]);
        $sales = D("admin")->where(array('employee_id'=>$workorder["sales_id"]))->find();
        $prescriber = D("admin")->where(array('employee_id'=>$workorder["prescriber_id"]))->find();

        $audit = D("Audit")->queryById($workorder["audit_id"]);
        $updater = D("admin")->where(array('employee_id'=>$audit["update_id"]))->find();

        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();

        $number = getBatchNo($user["enterprise_code"]);
        if(isNullOrEmpty($audit["batch_no"])){
            $batchNo = "00000000".substr(date('Ymd'),2,6).substr(strval($number+1000000),1,6);
            $audit["batch_no"] = $batchNo;

        }
        if(isNullOrEmpty($audit["audit_no"])){
            if($number < 10){
                $auditNo = "CP001-".date('Y')."-".substr(strval($number+100),1,2);
            }else{
                $auditNo = "CP001-".date('Y')."-".$number;
            }
            $audit["audit_no"] = $auditNo;
        }
        if(isNullOrEmpty($audit["batch_name"])){
            $audit["batch_name"] = "上/下肢医用外固定支具";
        }
        if(isNullOrEmpty($audit["mount"])){
            $audit["mount"] = "1 只";
        }
        if(isNullOrEmpty($audit["conclusion"])){
            $audit["conclusion"] = "外观检测合格，表面光滑，无裂痕，无毛刺，无擦痕；尺寸检测合格，准许出厂。";
        }

        $users_obj = M("admin");
        $userId = $_SESSION['ADMIN_ID'];
        $user = $users_obj->where("user_id=$userId")->find();
        if(in_role(array("1"),$user['role'])){
            $this->assign("adminUpdate", "true");
        }

        $this->assign("user", $user);
        $this->assign("patient", $patient);
        $this->assign("sales", $sales);
        $this->assign("prescriber", $prescriber);
        $this->assign("workorder", $workorder);
        $this->assign("audit", $audit);
        $this->assign("today", date('Y-m-d'));

        $enterprise=D("Enterprise")->where(array('enterprise_code'=>$user["enterprise_code"]))->find();
        $orthosisProcess = explode(',',$enterprise["orthosis_process"]);
        $this->assign('orthosisProcess', $orthosisProcess);

        $this->display();
    }

    public function audit_post() {

        $users_obj = M("admin");
        $userId = $_SESSION['ADMIN_ID'];
        $user = $users_obj->where("user_id=$userId")->find();

        $id = $_REQUEST["id"];
        $workorder = $this->currentModel->queryById($id);
        if (isNullOrEmpty($workorder["audit_id"])) {
            $auditId = D("Audit")->add(array(
                'status' => -1,
                'workorder_id' => $id,
            ));
            $workorder["audit_id"] = $auditId;
        }
        $audit = D("Audit")->queryById($workorder["audit_id"]);
        $audit["update_time"] = getCurrentDate();
        $audit["update_id"] = $user["employee_id"];
        $workorder["auditor_id"] = $user["employee_id"];

        $audit["batch_name"] = I('post.batch_name');
        $audit["customized_product_id"] = I('post.customized_product_id');
        $audit["mount"] = I('post.mount');
        $audit["conclusion"] = str_replace(array("\r\n", "\r", "\n"), "。", I('post.conclusion'));
        $audit["audit_date"] = I('post.audit_date');
        $audit["report_date"] = I('post.report_date');
        for($i = 0; $i <= 64; $i++){
            $audit["r".$i] = I("post.r".$i);
        }

        if(I('post.completed') == "on") {
            $audit["status"] = 1;
            $workorder["audit_status"] = 1;
            $workorder["audit_time"] = getCurrentDate();
            $workorder["review_status"] = 1;
            $workorder["review_time"] = getCurrentDate();
            $workorder["reviewer_id"] = 4;
            $patient = D("Patient")->queryById($workorder["patient_id"]);
            $sales = D("admin")->where(array('employee_id' => $workorder["sales_id"]))->find();
            $prescriber = D("admin")->where(array('employee_id' => $workorder["prescriber_id"]))->find();
            $creator = D("admin")->where(array('employee_id'=>$workorder["creator_id"]))->find();
            $number = getBatchNo($user["enterprise_code"]);
            if(isNullOrEmpty($audit["audit_no"])){
                if($number < 10){
                    $auditNo = "CP001-".date('Y')."-".substr(strval($number+100),1,2);
                }else{
                    $auditNo = "CP001-".date('Y')."-".$number;
                }
                $audit["audit_no"] = $auditNo;
            }
            if(isNullOrEmpty($audit["batch_no"])){
                $batchNo = "00000000".substr(date('Ymd'),2,6).substr(strval($number+1000000),1,6);
                $audit["batch_no"] = $batchNo;
                $batch_no = $audit["batch_no"];
                $batch = D("BatchNo")->where("batch_no=$batch_no")->find();
                if(isNullOrEmpty($batch)){
                    D("BatchNo")->add(array(
                        'date' => date('Y-m-d'),
                        'number' => $number,
                        'workorder_id' => $id,
                        'create_time' => getCurrentDate(),
                        'update_time' => getCurrentDate(),
                        'update_id' => $user["employee_id"],
                        'batch_no' => $audit["batch_no"],
                        'audit_no' => $audit["audit_no"],
                        'patient' => $patient["patient_name"],
                        'type' => $workorder["type_name"],
                        'enterprise_code' => $user["enterprise_code"],
                    ));
                }
                $workorder["batch_no"] = $audit["batch_no"];
            }

            //推送信息
            $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/workorder/index/id/" . $workorder["workorder_id"];
            $notifyData["first"] = "工单“" . $workorder["workorder_no"] . "”已经由 " . $user["admin_name"] . " 完成[成品质量检验]。";
            $notifyData["keyword1"] = "患者：" . $patient["patient_name"] . " ".$workorder["side"]."，" . $patient["sex"] . "，" . $patient["age"] . "岁。[诊断--" . $patient["diagnosis"] . "]";
            $notifyData["keyword2"] = getCurrentDate();
            $notifyData["keyword3"] = "制作人员、库管";
            $notifyData["remark"] = "下单人：" . $creator["admin_name"] . "，业务员：" . $sales["admin_name"] . "。处方人：" . $prescriber["admin_name"];

//            $adminRoleArr = array("1", "5", "8", "9");
//            $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
            $openidArray = getNotifyArrByName("auditEndWorkorder", $user["enterprise_code"]);
            $openidArray = array_unique($openidArray);
            foreach ($openidArray as $openid) {
                $notifyData["openid"] = $openid;
                WorkorderProcessingNotify($notifyData);
            }
        }
        D("Workorder")->updateInfo($workorder);
        D("Audit")->updateInfo($audit);
        $this->success("已完成 成品质量检验", U("Workorder/index"));

    }

    public function review() {

        $id = $_REQUEST["id"];
        $workorder = $this->currentModel->queryById($id);
        $workorder["review_status"] = 1;
        $workorder["review_time"] = getCurrentDate();

        $this->currentModel->updateInfo($workorder);

        $processId = $workorder["process_id"];
        $process = D("Process")->queryById($processId);
        $statusArr=explode(",",$process["status"]);
        $statusArr[12] = "1";
        $i = 0;
        foreach ($statusArr as $statusValue) {
            if($i == 0){
                $process["status"] = $statusValue;
            }else{
                $process["status"] .= "," . $statusValue;
            }

            $i++;
        }
        $workorder["process_status"] = $process["status"];

        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();
        $workorder["reviewer_id"] = $user["employee_id"];
        D("Workorder")->updateInfo($workorder);
        D("Process")->updateInfo($process);

        //推送留言信息到处方人审核人
        $patient = D("Patient")->queryById($workorder["patient_id"]);
        $sales = D("admin")->where(array('employee_id'=>$workorder["sales_id"]))->find();
        $prescriber = D("admin")->where(array('employee_id'=>$workorder["prescriber_id"]))->find();
        $creator = D("admin")->where(array('employee_id'=>$workorder["creator_id"]))->find();
        $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/workorder/index/id/" . $workorder["workorder_id"];
        $notifyData["first"] = "工单“".$workorder["workorder_no"]."”已经由 " . $user["admin_name"] . " 完成工序检查，请质检人进行审核。";
        $notifyData["keyword1"] = "患者：" . $patient["patient_name"] . " ".$workorder["side"]."，" . $patient["sex"] . "，" . $patient["age"] . "岁。[诊断--" . $patient["diagnosis"] . "]";
        $notifyData["keyword2"] = getCurrentDate();
        $notifyData["keyword3"] = "质检人";
        $notifyData["remark"] = "下单人：" . $creator["admin_name"] . "，业务员：" . $sales["admin_name"] . "。处方人：" . $prescriber["admin_name"];

        $adminRoleArr = array("1","9");
        $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
        array_push($openidArray, $prescriber["openid"]);
        $openidArray = array_unique($openidArray);
        foreach ($openidArray as $openid) {
            $notifyData["openid"] = $openid;
            WorkorderProcessingNotify($notifyData);
        }

        $this->success("已完成工序检查", U("Workorder/index"));
    }

    public function claimMaterial() {
        $id = $_REQUEST["id"];
        $workorder = $this->currentModel->queryById($id);

        $users_obj = M("admin");
        $userId = $_SESSION['ADMIN_ID'];
        $user = $users_obj->where("user_id=$userId")->find();
        $patient = D("Patient")->queryById($workorder["patient_id"]);
        $sales = D("admin")->where(array('employee_id'=>$workorder["sales_id"]))->find();
        $prescriber = D("admin")->where(array('employee_id'=>$workorder["prescriber_id"]))->find();
        $claimAuditor = D("admin")->where(array('employee_id'=>$workorder["claim_auditor_id"]))->find();
        $claimer = D("admin")->where(array('employee_id'=>$workorder["claimer_id"]))->find();

        $this->assign("patient", $patient);
        $this->assign("sales", $sales);
        $this->assign("prescriber", $prescriber);
        $this->assign("claimer", $claimer);
        $this->assign("claimAuditor", $claimAuditor);
        $this->assign("workorder", $workorder);



        $map["workorder_no"] = $workorder["workorder_no"];
        $list = D("ClaimMaterial")->queryForList(null, $map);

        $listCode = D('Code')->alias("c")
            ->join("left join __CODE__ p on p.code_id = c.parentid")
            ->join("left join __MATERIAL__ m on m.code_id = c.code_id")
            ->where(array('c.level' => 1, 'c.enterprise_code'=>$user["enterprise_code"]))
            ->field("c.*, c.name as code_name, p.name as parent_name, m.material_name, m.spec, m.prop, m.unit, m.barcode")
            ->select();

        $listStorage = D('Storage')->alias("st")
            ->join("left join __MATERIAL__ m on m.code_id = st.code_id")
            ->where(array('st.enterprise_code'=>$user["enterprise_code"]))
            ->field("st.*, m.unit, m.barcode")
            ->select();

        $this->assign('listCode', $listCode);
        $this->assign('listStorage', $listStorage);
        $this->assign("user", $user);
        $this->assign("list", $list);
        $this->assign("row", count($list));

        $enterprise=D("Enterprise")->where(array('enterprise_code'=>$user["enterprise_code"]))->find();
        $orthosisProcess = explode(',',$enterprise["orthosis_process"]);
        $this->assign('orthosisProcess', $orthosisProcess);

        $this->display("claimMaterial");
    }

    public function claimMaterialPost() {

        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();

        $id = $_REQUEST["id"];
        $workorder = D("Workorder")->queryById($id);
        $oldList = D("ClaimMaterial")->where(array('workorder_no'=>$workorder["workorder_no"]))->select();
        if($_REQUEST["btnText"] == "领料"){
            $workorder["material_store_id"] = $_REQUEST["store_id"];
            $workorder["material_remark"] = $_REQUEST["remark"];
            $workorder["claim_date"] = $_REQUEST["claim_date"];
            $workorder["claimer_id"] = $user["employee_id"];
            $workorder["claim_status"] = -1;
            D("Workorder")->updateInfo($workorder);
            $row = $_REQUEST["row"];
            $idArr = array();
            for($i = 0; $i < $row; $i++){
                if(isNullOrEmpty($_REQUEST["code_id_".$i])){
                    continue;
                }
                $tmpData = null;
                $tmpData["status"] = 1;
                $tmpData["claim_material_id"] = $_REQUEST["claim_material_id_".$i];
                $tmpData["workorder_no"] = $workorder["workorder_no"];
                $tmpData["code_id"] = $_REQUEST["code_id_".$i];
                $tmpData["batch_no"] = $_REQUEST["batch_no_".$i];
                $tmpData["store_id"] = $_REQUEST["store_id"];
                $tmpData["supplier_id"] = $_REQUEST["supplier_id_".$i];
                $tmpData["number"] = $_REQUEST["number_".$i];
                $tmpData["total_price"] = $_REQUEST["total_price_".$i];
                $tmpData["update_time"] = getCurrentDate();
                $tmpData["update_id"] = $user["employee_id"];
                if(isNullOrEmpty($tmpData["claim_material_id"])){
                    $tmpData["create_time"] = getCurrentDate();
                    $tmpData["enterprise_code"] = $user["enterprise_code"];
                    D("ClaimMaterial")->add($tmpData);
                }else{
                    D("ClaimMaterial")->updateInfo($tmpData);
                    array_push($idArr, $tmpData["claim_material_id"]);
                }

                $tmpData["type"] = "物料";
                $tmpStorage = D("Storage")
                    ->where(array('type'=>'物料',
                        'enterprise_code'=>$user["enterprise_code"],
                        'code_id'=>$tmpData["code_id"],
                        'store_id'=>$tmpData["store_id"],
                        'batch_no'=>$tmpData["batch_no"]))
                    ->find();
                if(!isNullOrEmpty($tmpStorage)){
                    if($tmpStorage["storage_number"] == $tmpData["number"]){
                        D("Storage")->where(array("storage_id" => $tmpData["storage_id"]))->delete();
                    }else{
                        $tmpStorage["storage_number"] -= $tmpData["number"];
                        $tmpStorage["update_time"] = getCurrentDate();
                        $tmpStorage["update_id"] = $user["employee_id"];
                        D("Storage")->updateInfo($tmpStorage);
                    }
                }else{
                    $tmpData["type"] = "物料";
                    $tmpData["storage_number"] *= -1;
                    $tmpData["create_time"] = getCurrentDate();
                    $tmpData["update_time"] = getCurrentDate();
                    $tmpData["update_id"] = $user["employee_id"];
                    D("Storage")->add($tmpData);
                }
            }

            foreach ($oldList as $old){
                if (!in_array($old["claim_material_id"], $idArr)) {
                    D("ClaimMaterial")->deleteById($old["claim_material_id"]);
                }
            }
            $this->success("领料成功，工单号：".$workorder["workorder_no"], U("Workorder/index"));
        }
        if($_REQUEST["btnText"] == "反审核" || $_REQUEST["btnText"] == "拒绝"){
            $workorder["claim_status"] = -2;
            $workorder["claim_auditor_id"] = $user["employee_id"];
            $workorder["claim_audit_date"] = $_REQUEST["claim_audit_date"];
            $workorder["claim_audit_note"] = $_REQUEST["claim_audit_note"];
            D("Workorder")->updateInfo($workorder);

            $List = D("ClaimMaterial")->where(array('workorder_no'=>$workorder["workorder_no"]))->select();
            foreach ($List as $tmpData){
                $tmpData["update_time"] = getCurrentDate();
                $tmpData["status"] = -1;
                D("ClaimMaterial")->updateInfo($tmpData);
                $tmpData["type"] = "物料";
                $tmpStorage = D("Storage")
                    ->where(array('type'=>'物料',
                        'enterprise_code'=>$user["enterprise_code"],
                        'code_id'=>$tmpData["code_id"],
                        'store_id'=>$tmpData["store_id"],
                        'batch_no'=>$tmpData["batch_no"]))
                    ->find();
                if(isNullOrEmpty($tmpStorage)){
                    $tmpData["storage_number"] = $tmpData["number"];
                    D("Storage")->add($tmpData);
                }else{
                    $tmpStorage["storage_number"] += $tmpData["number"];
                    $tmpStorage["update_time"] = getCurrentDate();
                    $tmpStorage["update_id"] = $user["employee_id"];
                    D("Storage")->updateInfo($tmpStorage);
                }

            }

            $this->success("领料" . $_REQUEST["btnText"] . "成功，单号：".$workorder["workorder_no"], U("Workorder/index"));
        }
        if($_REQUEST["btnText"] == "审核"){
            $workorder["claim_status"] = 1;
            $workorder["claim_auditor_id"] = $user["employee_id"];
            $workorder["claim_audit_date"] = $_REQUEST["claim_audit_date"];
            $workorder["claim_audit_note"] = $_REQUEST["claim_audit_note"];
            D("Workorder")->updateInfo($workorder);

//            $List = D("ClaimMaterial")->where(array('workorder_no'=>$workorder["workorder_no"]))->select();
//            foreach ($List as $tmpData){
//                $tmpData["type"] = "物料";
//                $tmpStorage = D("Storage")
//                    ->where(array('type'=>'物料',
//                        'enterprise_code'=>$user["enterprise_code"],
//                        'code_id'=>$tmpData["code_id"],
//                        'store_id'=>$tmpData["store_id"],
//                        'batch_no'=>$tmpData["batch_no"]))
//                    ->find();
//                if(!isNullOrEmpty($tmpStorage)){
//                    if($tmpStorage["storage_number"] == $tmpData["number"]){
//                        D("Storage")->where(array("storage_id" => $tmpData["storage_id"]))->delete();
//                    }else{
//                        $tmpStorage["storage_number"] -= $tmpData["number"];
//                        $tmpStorage["update_time"] = getCurrentDate();
//                        $tmpStorage["update_id"] = $user["employee_id"];
//                        D("Storage")->updateInfo($tmpStorage);
//                    }
//                }else{
//                    $tmpData["type"] = "物料";
//                    $tmpData["storage_number"] *= -1;
//                    $tmpData["create_time"] = getCurrentDate();
//                    $tmpData["update_time"] = getCurrentDate();
//                    $tmpData["update_id"] = $user["employee_id"];
//                    D("Storage")->add($tmpData);
//                }
//            }

            $this->success("领料审核成功，单号：".$workorder["workorder_no"], U("Workorder/index"));
        }
    }

    public function outstore() {
        $id = $_REQUEST["id"];
        $workorder = $this->currentModel->queryById($id);
        $this->assign("workorder", $workorder);

        $users_obj = M("admin");
        $userId = $_SESSION['ADMIN_ID'];
        $user = $users_obj->where("user_id=$userId")->find();
        $patient = D("Patient")->queryById($workorder["patient_id"]);
        $sales = D("admin")->where(array('employee_id'=>$workorder["sales_id"]))->find();
        $prescriber = D("admin")->where(array('employee_id'=>$workorder["prescriber_id"]))->find();
        $this->assign("user", $user);
        $this->assign("patient", $patient);
        $this->assign("sales", $sales);
        $this->assign("prescriber", $prescriber);

        $outstore = D("Instore")->alias("i")
            ->where(array("product_id"=>$workorder["workorder_id"]))
            ->find();
        if(isNullOrEmpty($outstore["outstore_name"])){
            $outstore["outstore_name"] = $outstore["inventory_name"];
        }
        if(isNullOrEmpty($outstore["outstore_auditor_id"])){
            $outstoreAuditor = D("admin")->where(array('employee_id'=>$user["employee_id"]))->find();
        }else{
            $outstoreAuditor = D("admin")->where(array('employee_id'=>$outstore["outstore_auditor_id"]))->find();
        }

        $listClientInfo = D('ClientInfo')->where(array('enterprise_code'=>$user["enterprise_code"]))->select();
        $this->assign("outstore", $outstore);
        $this->assign("workorder", $workorder);
        $this->assign("outstoreAuditor", $outstoreAuditor);

        $enterprise=D("Enterprise")->where(array('enterprise_code'=>$user["enterprise_code"]))->find();
        $orthosisProcess = explode(',',$enterprise["orthosis_process"]);
        $this->assign('orthosisProcess', $orthosisProcess);

        $this->display("outstore");
    }

    public function outstorePost() {

        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();

        $id = $_REQUEST["id"];
        $workorder = D("Workorder")->queryById($id);
        $outstore = D("Instore")->where(array("product_id"=>$workorder["workorder_id"]))->find();

        if($_REQUEST["btnText"] == "出库反审核"){
            $workorder["outstore_status"] = -1;
            D("Workorder")->updateInfo($workorder);
            D("Instore")->updateInfo($outstore);
            $this->success("销售出库反审核成功，单号：".$workorder["workorder_no"], U("Workorder/index"));
        }

//        $outstore["outstore_auditor_id"] = $_REQUEST["outstore_auditor"];
        $outstore["outstore_date"] = $_REQUEST["outstore_date"];
        $outstore["outstore_update_time"] = getCurrentDate();
        $outstore["client_info_id"] = $_REQUEST["client_info_id"];
        $outstore["contact"] = $_REQUEST["contact"];
        $outstore["mobile"] = $_REQUEST["mobile"];
        $outstore["address"] = $_REQUEST["address"];
//        $outstore["outstore_store_id"] = $_REQUEST["outstore_store_id"];
        $outstore["payment_status"] = $_REQUEST["payment_status"];
        $outstore["payment_price"] = $_REQUEST["payment_price"];
        $outstore["express_company"] = $_REQUEST["express_company"];
        $outstore["delivery_number"] = $_REQUEST["delivery_number"];
        $outstore["delivery_place"] = $_REQUEST["delivery_place"];
        $outstore["outstore_name"] = $_REQUEST["outstore_name"];
        $outstore["sale_price"] = $_REQUEST["sale_price"];
        $outstore["remark"] = $_REQUEST["remark"];

        if($_REQUEST["btnText"] == "更新"){
            D("Instore")->updateInfo($outstore);
            $this->success("销售出库内容更新成功，工单号：".$workorder["workorder_no"], U("Workorder/index"));
        }

        if($_REQUEST["btnText"] == "出库审核"){
            $workorder["outstore_status"] = 1;
            D("Workorder")->updateInfo($workorder);
            $outstore["outstore_status"] = 1;
            D("Instore")->updateInfo($outstore);
            $this->success("销售出库审核成功，工单号：".$workorder["workorder_no"], U("Workorder/index"));
        }

    }
}

